java 通过 smtp 服务 给指定邮箱发送邮件 可包含附件

用程序发邮件首先需要一个smtp服务器,

虽然说网上也有自建服务器的教程,但是由于工程量大,

还要兼容各大邮箱厂商,有可能发送失败或被归为垃圾邮件。

所以不推荐自建smtp服务器实现。

推荐是有2种方法来实现 第三方邮箱发邮件

1、买类似阿里云的smtp资源包(阿里云 1000条 / 2元)
2、申请一个腾讯、网易163的邮箱,开通smtp服务端口,借由他们的服务器来转发。

(其中部分第三方邮箱可以实现用自己的域名来接发邮件,例如service@baidu.com)

本文中介绍的是第二种方法,用腾讯企业邮箱为例

参考借鉴的大神的原文地址:https://www.cnblogs.com/LUA123/p/5575134.html

这里重点只说明一下,腾讯企业邮箱 + javamail 来实现发邮件,代码的部分。

其他邮箱,例如个人的qq邮箱 163邮箱也可以用这个方法实现,申请和设置方法借鉴百度吧

补充一下!腾讯企业邮箱和qq邮箱方法有几个不同,我在末尾加了qq邮箱的方案

正文开始

先说腾讯企业邮箱

maven

  1. <dependency>
  2. <groupId>javax.mail</groupId>
  3. <artifactId>mail</artifactId>
  4. <version>1.4.7</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.commons</groupId>
  8. <artifactId>commons-lang3</artifactId>
  9. <version>3.7</version>
  10. </dependency>

java 工具类
需要把 用户名、密码、发件人别名 等参数填成你自己申请的
EmailUtils.java

  1. package com.gemini.common.utils;
  2. import com.sun.mail.util.MailSSLSocketFactory;
  3. import org.apache.commons.lang.StringUtils;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.security.GeneralSecurityException;
  7. import java.util.Date;
  8. import java.util.Properties;
  9. import javax.mail.Authenticator;
  10. import javax.mail.Message;
  11. import javax.mail.MessagingException;
  12. import javax.mail.Multipart;
  13. import javax.mail.PasswordAuthentication;
  14. import javax.mail.Session;
  15. import javax.mail.Transport;
  16. import javax.mail.internet.InternetAddress;
  17. import javax.mail.internet.MimeBodyPart;
  18. import javax.mail.internet.MimeMessage;
  19. import javax.mail.internet.MimeMultipart;
  20. public class EmailUtils {
  21. // 腾讯企业邮箱 也可以换成别家的
  22. private static final String protocol = "smtp";// 协议
  23. private static final String host = "smtp.exmail.qq.com";// 地址
  24. private static final String port = "465";// 端口
  25. private static final String account = "用户名";// 用户名
  26. private static final String pass = "密码";// 密码
  27. private static final String personal = "发件人别名(选填)";// 发件人别名,不需要设为空串或null
  28. // 权限认证
  29. static class MyAuthenricator extends Authenticator {
  30. String u = null;
  31. String p = null;
  32. public MyAuthenricator(String u, String p) {
  33. this.u = u;
  34. this.p = p;
  35. }
  36. @Override
  37. protected PasswordAuthentication getPasswordAuthentication() {
  38. return new PasswordAuthentication(u, p);
  39. }
  40. }
  41. /**
  42. * 发送邮件工具方法
  43. *
  44. * @param recipients 收件人
  45. * @param subject 主题
  46. * @param content 内容
  47. * @param fileStr 附件路径
  48. * @return true/false 发送成功
  49. */
  50. public static boolean sendEmail(String recipients, String subject, String content, String fileStr) {
  51. Properties prop = new Properties();
  52. //协议
  53. prop.setProperty("mail.transport.protocol", protocol);
  54. //服务器
  55. prop.setProperty("mail.smtp.host", host);
  56. //端口
  57. prop.setProperty("mail.smtp.port", port);
  58. //使用smtp身份验证
  59. prop.setProperty("mail.smtp.auth", "true");
  60. //使用SSL,企业邮箱必需!
  61. //开启安全协议
  62. MailSSLSocketFactory mailSSLSocketFactory = null;
  63. try {
  64. mailSSLSocketFactory = new MailSSLSocketFactory();
  65. mailSSLSocketFactory.setTrustAllHosts(true);
  66. } catch (GeneralSecurityException e1) {
  67. e1.printStackTrace();
  68. }
  69. prop.put("mail.smtp.ssl.enable", "true");
  70. prop.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
  71. Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass));
  72. session.setDebug(true);
  73. MimeMessage mimeMessage = new MimeMessage(session);
  74. try {
  75. //发件人
  76. if (StringUtils.isNotBlank(personal))
  77. mimeMessage.setFrom(new InternetAddress(account, personal));//可以设置发件人的别名
  78. else
  79. mimeMessage.setFrom(new InternetAddress(account));//如果不需要就省略
  80. //收件人
  81. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
  82. //主题
  83. mimeMessage.setSubject(subject);
  84. //时间
  85. mimeMessage.setSentDate(new Date());
  86. //容器类,可以包含多个MimeBodyPart对象
  87. Multipart mp = new MimeMultipart();
  88. //MimeBodyPart可以包装文本,图片,附件
  89. MimeBodyPart body = new MimeBodyPart();
  90. //HTML正文
  91. body.setContent(content, "text/html; charset=UTF-8");
  92. mp.addBodyPart(body);
  93. //添加图片&附件
  94. if(StringUtils.isNotBlank(fileStr)){
  95. body = new MimeBodyPart();
  96. body.attachFile(fileStr);
  97. mp.addBodyPart(body);
  98. }
  99. //设置邮件内容
  100. mimeMessage.setContent(mp);
  101. //仅仅发送文本
  102. //mimeMessage.setText(content);
  103. mimeMessage.saveChanges();
  104. Transport.send(mimeMessage);
  105. // 发送成功
  106. return true;
  107. } catch (MessagingException e) {
  108. e.printStackTrace();
  109. } catch (UnsupportedEncodingException e) {
  110. e.printStackTrace();
  111. } catch (IOException e) {
  112. e.printStackTrace();
  113. }
  114. return false;
  115. }
  116. public static void main(String[] args) {
  117. sendEmail("你的邮箱地址","test","test",null);
  118. }
  119. }

关于上述方案,适用于一般的邮箱申请(腾讯企业邮箱、网易邮箱),但不适用于qq邮箱,原因是qq邮箱目前只接受授权码方案登录,官方的解释是“温馨提示:在第三方登录QQ邮箱,可能存在邮件泄露风险,甚至危害Apple ID安全,建议使用QQ邮箱手机版登录。 继续获取授权码登录第三方客户端邮箱 。”

使用上述方法登录qq邮箱会遇到报错

javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿´: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

意思就是不支持直接用默认密码登录,必须去申请一个授权码作为密码登录

其实流程和工具类都一样就重点说 2个不一样的地方

1、密码不是你的邮箱密码了,而是授权码。

获取方式 [登录邮箱] - [设置] - [账户] ,然后如下图找到POP3/SMTP服务的下面,有一句温馨提示 先点 [生成授权码] ,再根据提示获取到授权码。

授权码就是javamail里的password

2、host不同

腾讯企业邮箱的host是

private static final String host = "smtp.exmail.qq.com";// 地址
普通qq邮箱的host是

private static final String host = "smtp.qq.com";// 地址

修改这两个地方即可适用于个人普通的qq邮箱

送人玫瑰,手留余香
自制可爱风格的服务器错误页面 猫抓毛线球
windows桌面美化,一步变高科技。rainmeter入门