这篇文章主要为大家分享了java实现163邮箱发送邮件到QQ邮箱成功案例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
下载和上传附件、发送短信和发送邮件,都算是程序中很常用的功能,之前记录了文件的上传和下载还有发送短信,由于最近比较忙,邮件发送的功能就没有时间去弄,现在终于成功以163邮箱发送邮件到QQ邮箱,以下是相关代码,具体解释可以参考代码中注释:
package test; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.sun.mail.util.MailSSLSocketFactory; ///** // * // * @author tuzongxun123 // * @Description 邮件发送测试类 // */ public class sendMailTest { public static void main(String[] args) throws Exception { // 配置信息 Properties pro = new Properties(); pro.put("mail.smtp.host", "smtp.163.com"); pro.put("mail.smtp.auth", "true"); // SSL加密 MailSSLSocketFactory sf = null; sf = new MailSSLSocketFactory(); // 设置信任所有的主机 sf.setTrustAllHosts(true); pro.put("mail.smtp.ssl.enable", "true"); pro.put("mail.smtp.ssl.socketFactory", sf); // 根据邮件的会话属性构造一个发送邮件的Session,这里需要注意的是用户名那里不能加后缀,否则便不是用户名了 //还需要注意的是,这里的密码不是正常使用邮箱的登陆密码,而是客户端生成的另一个专门的授权码 MailAuthenticator authenticator = new MailAuthenticator("tuzongxun123", "客户端授权码"); Session session = Session.getInstance(pro, authenticator); // 根据Session 构建邮件信息 Message message = new MimeMessage(session); // 创建邮件发送者地址 Address from = new InternetAddress("[email protected]"); // 设置邮件消息的发送者 message.setFrom(from); // 验证收件人邮箱地址 List toAddressList = new ArrayList(); toAddressList.add("[email protected]"); StringBuffer buffer = new StringBuffer(); if (!toAddressList.isEmpty()) { String regEx = "^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$"; Pattern p = Pattern.compile(regEx); for (int i = 0; i fileAddressList = new ArrayList(); fileAddressList .add("C:\Users\tuzongxun123\Desktop\新建 Microsoft Office Word 文档.docx"); if (fileAddressList != null) { BodyPart attchPart = null; for (int i = 0; i
注:我有个同事使用我这个代码更换为他的账号和客户端授权码后,一运行就报错,然后重置了一下邮箱的客户端授权码后,错误便消失了。
以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。