Java发送点子邮件E-mail,主要是利用java.mail.*包。发送邮件需要包含三部分:
发送人邮箱地址:String:mailFrom,这个是一个点子邮件的地址,比如 zhangsan@126.com
发送人邮件的密码:String:mailPwd,比如:123456789;
发送人发送这个邮件所需的发送服务器:String :mailHost,比如:smtp.126.com;
收件人地址,String mailTo,比如lisi@163.com;
邮件主题,String mailSubject
邮件内容:String mailContent
public boolean PostMail(String mailFrom,String,mailPwd,String mailHost,String mailTo,String mailSubject,String mailContent) { String subject=mailSubject; String content=mailContent; String host = mailHost; String from = mailFrom String pwd=mailPwd;
Stirng to=mailTo;
Properties props = System.getProperties(); // 设置邮件服务器 props.put("mail.smtp.host", host); // 取得 session props.put("mail.smtp.auth", "true");// 设置验证 MyAuthenticator myauth = new MyAuthenticator(from, pwd); Session session = Session.getDefaultInstance(props, (Authenticator)myauth); MimeMessage message = new MimeMessage(session); try { // 发送邮件地址 message.setFrom(new InternetAddress(from)); // 接收邮件地址 message.addRecipient(Message.RecipientType.TO, new InternetAddress( to)); message.setSubject(subject);// 设置邮件主题 // 设定邮件内容 BodyPart mdp = new MimeBodyPart();// 创建一个存放邮件内容的BodyPart对象 mdp.setContent(content, "text/html;charset=gbk");// 给BodyPart对象设内容和格式 Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对象,(它可以存储多个) mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个Bodypart) message.setContent(mm);// 把mm作为消息对象的内容 message.saveChanges(); message.setSentDate(new java.util.Date()); Transport.send(message); System.out.print("邮件发送成功!"); return true; } catch (Exception e) { System.out.print("邮件发送失败!"); e.printStackTrace(); return false; } }