通过javaMail发送邮件,可选添加多个收件人,密送,抄送,多个附件

通过javaMail发送邮件,可选添加多个收件人,密送,抄送,多个附件

https://blog.csdn.net/qq_35434831/article/details/79666035

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35434831/article/details/79666035

        自己通过学习多人的代码,并整理了一个简单,调用方便的通过javaMail发送邮件。只需填写发件邮箱地址,密码;收件人地址,附件,选择是否保存,设置自己发送邮件时的昵称就ok了。代码自动匹配设置smtp服务地址和端口。

    发送邮件需要邮箱地址和密码,开启POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务。各大邮箱使用外部登录验证的方式不一样,有些需要使用授权码登录链接,有些只需要邮箱登录密码,这个得根据你使用的邮箱服务平台的规定了。这里我收集了下面的邮箱smtp服务地址和端口,【QQ、Foxmail、139、126、163、Google(gmail)、Exchange、Outlook、sina.cn、sina.com】这些足以够用了吧!不多说,看代码。

    使用方法

 
  1. public static void main(String[] args) throws Exception {

  2.  
  3. List<String> map = new ArrayList<>();

  4. map.add("123456@qq.com");

  5. map.add("456789@qq.com");

  6. map.add("hahaha123@gmail.com");

  7. new SendEmail("hahaha123@gmail.com", "密码")

  8. .setDebug(true)

  9. .setMyNickName("这是我的昵称")

  10. .addFile("C:/Users/25171/Pictures/timg.jpg")//添加附件

  11. .addFile("C:/Users/25171/Desktop/QQ图片20180317192741.jpg")

  12. // .addFile(List<String> list)//添加附件集合

  13. .setSaveEmail("C:/User/2517/Desktop/name.eml")//保存邮件

  14. .addRecipientT0("251716795@qq.com")//添加收件人地址

  15. // .addRecipientT0(map)//添加收件人地址集合

  16. // .addRecipientCC(map)//添加密送收件人地址

  17. // .addRecipientBCC(map)//添加抄送收件人地址

  18. .createMail("标题", "发送的内容", "text/html;charset=utf-8")

  19. .sendEmail(new SendEmail.Callback() {

  20. @Override

  21. public void success(String s) {

  22. System.out.println(s);//发送完成后回调接口

  23. }

  24.  
  25. @Override

  26. public void error(String s, Exception e) {

  27. System.out.println(s);

  28. e.printStackTrace();//异常失败的回调接口

  29. }

  30. });

  31. }

主体工具代码

 
  1. package com.sai.mail;

  2.  
  3. import javax.activation.DataHandler;

  4. import javax.activation.FileDataSource;

  5. import javax.mail.*;

  6. import javax.mail.internet.*;

  7. import java.io.FileOutputStream;

  8. import java.io.IOException;

  9. import java.io.OutputStream;

  10. import java.io.UnsupportedEncodingException;

  11. import java.util.*;

  12.  
  13. public class SendEmail {

  14.  
  15. public interface Callback {

  16. void success(String s);

  17.  
  18. void error(String s, Exception e);

  19. }

  20.  
  21. private Callback callback; //信息回调接口

  22. private Properties properties;//系统属性对象

  23. private String mailAccount; //发送邮箱地址

  24. private String mailPassword; //验证密码

  25. private Session session; //邮件会话对象

  26. private String myNickName; //昵称,发送时自己的昵称

  27. private boolean debug = false;//debug模式

  28. private boolean isSaveEmail = false;

  29. private String pathName = "exc.eml";//邮件保存时的

  30.  
  31. public SendEmail(String mailAccount, String mailPassword) {

  32. this.mailAccount = mailAccount;

  33. this.mailPassword = mailPassword;

  34. }

  35.  
  36. public SendEmail setSaveEmail(String pathName) {

  37. isSaveEmail = true;

  38. this.pathName = pathName;

  39. return this;

  40. }

  41.  
  42. private List<String> recipientT0List = new ArrayList<>();//收件地址

  43. private List<String> recipientCCList = new ArrayList<>();//密送地址

  44. private List<String> recipientBCCList = new ArrayList<>();//抄送地址

  45. private List<String> filePath = new ArrayList<>();//附件

  46.  
  47. public SendEmail setDebug(boolean sessionDebug) {

  48. debug = sessionDebug;

  49. return this;

  50. }

  51.  
  52. /*** 设置多人收件人地址 */

  53. public SendEmail addRecipientT0(String address) {

  54. recipientT0List.add(address);

  55. return this;

  56. }

  57.  
  58. public SendEmail addRecipientCC(String address) {

  59. recipientCCList.add(address);

  60. return this;

  61. }

  62.  
  63. public SendEmail addRecipientBCC(String address) {

  64. recipientBCCList.add(address);

  65. return this;

  66. }

  67.  
  68. public SendEmail addRecipientT0(List<String> address) {

  69. recipientT0List.addAll(address);

  70. return this;

  71. }

  72.  
  73. public SendEmail addRecipientCC(List<String> address) {

  74. recipientCCList.addAll(address);

  75. return this;

  76. }

  77.  
  78. public SendEmail addRecipientBCC(List<String> address) {

  79. recipientBCCList.addAll(address);

  80. return this;

  81. }

  82.  
  83. /***添加文件***/

  84. public SendEmail addFile(String filePath) {

  85. this.filePath.add(filePath);

  86. return this;

  87. }

  88.  
  89. public SendEmail addFile(List<String> list) {

  90. this.filePath.addAll(list);

  91. return this;

  92. }

  93.  
  94. /****昵称设置**/

  95. public SendEmail setMyNickName(String name) {

  96. myNickName = name;

  97. return this;

  98. }

  99.  
  100. private MimeMessage message;

  101.  
  102. /**

  103. * @param title 主题

  104. * @param datas 内容

  105. * @param type 内容格式类型 text/html;charset=utf-8

  106. * @return s

  107. */

  108. public SendEmail createMail(String title, String datas, String type) {

  109. if (mailAccount.length() == 0 || mailAccount.equals(null)) {

  110. System.err.println("发件地址不存在!");

  111. return this;

  112. }

  113. if (myNickName == null) {

  114. myNickName = mailAccount;

  115. }

  116. getProperties();

  117. if (!sync) return this;

  118. try {

  119. message = new MimeMessage(session);

  120. // 设置发送邮件地址,param1 代表发送地址 param2 代表发送的名称(任意的) param3 代表名称编码方式

  121. message.setFrom(new InternetAddress(mailAccount, myNickName, "utf-8"));

  122.  
  123. setRecipientT0(); //添加接收人地址

  124. setRecipientCC(); //添加抄送接收人地址

  125. setRecipientBCC(); //添加密送接收人地址

  126. BodyPart messageBodyPart = new MimeBodyPart(); // 创建消息部分

  127. Multipart multipart = new MimeMultipart(); // 创建多重消息

  128.  
  129. messageBodyPart.setContent(datas, type); // 消息内容

  130. multipart.addBodyPart(messageBodyPart); // 设置文本消息部分

  131.  
  132. addFile(multipart); //附件部分

  133. // 发送完整消息

  134. message.setContent(multipart);

  135. message.setSubject(title); // 设置邮件主题

  136. message.setSentDate(new Date()); // 设置发送时间

  137. message.saveChanges(); // 保存上面的编辑内容

  138. // 将上面创建的对象写入本地

  139. saveEmail(title);

  140. } catch (Exception e) {

  141. if (callback != null)

  142. callback.error("message error ", e);

  143. sync = false;

  144. }

  145. return this;

  146. }

  147.  
  148. public void sendEmail(Callback callback) {

  149. this.callback = callback;

  150. if (!sync)

  151. return;

  152. try {

  153. Transport trans = session.getTransport();

  154. // 链接邮件服务器

  155. trans.connect(mailAccount, mailPassword);

  156. // 发送信息

  157. trans.sendMessage(message, message.getAllRecipients());

  158. // 关闭链接

  159. trans.close();

  160. if (callback != null)

  161. callback.success("发送完成");

  162. } catch (Exception e) {

  163. if (callback != null)

  164. callback.error("发送异常", e);

  165. }

  166. }

  167.  
  168. private void saveEmail(String title) throws IOException, MessagingException {

  169. OutputStream out = null;

  170. if (isSaveEmail) {

  171. if (pathName.length() == 0 || pathName.equals(null)) {

  172. out = new FileOutputStream(title + ".eml");

  173. } else {

  174. String path[] = pathName.split("\\.");

  175. out = new FileOutputStream(path[0] + title + ".eml");

  176. }

  177. }

  178. message.writeTo(out);

  179. out.flush();

  180. out.close();

  181. }

  182.  
  183. /*** 设置收件人地址信息*/

  184. private void setRecipientT0() throws MessagingException, UnsupportedEncodingException {

  185. if (recipientT0List.size() > 0) {

  186. InternetAddress[] sendTo = new InternetAddress[recipientT0List.size()];

  187. for (int i = 0; i < recipientT0List.size(); i++) {

  188. System.out.println("发送到:" + recipientT0List.get(i));

  189. sendTo[i] = new InternetAddress(recipientT0List.get(i), "", "UTF-8");

  190. }

  191. message.addRecipients(MimeMessage.RecipientType.TO, sendTo);

  192. }

  193. }

  194.  
  195. /***设置密送地址**/

  196. private void setRecipientCC() throws MessagingException, UnsupportedEncodingException {

  197. if (recipientCCList.size() > 0) {

  198. InternetAddress[] sendTo = new InternetAddress[recipientCCList.size()];

  199. for (int i = 0; i < recipientCCList.size(); i++) {

  200. System.out.println("发送到:" + recipientCCList.get(i));

  201. sendTo[i] = new InternetAddress(recipientCCList.get(i), "", "UTF-8");

  202. }

  203. message.addRecipients(MimeMessage.RecipientType.CC, sendTo);

  204. }

  205. }

  206.  
  207. /***设置抄送邮件地址**/

  208. private void setRecipientBCC() throws MessagingException, UnsupportedEncodingException {

  209. if (recipientBCCList.size() > 0) {

  210. InternetAddress[] sendTo = new InternetAddress[recipientBCCList.size()];

  211. for (int i = 0; i < recipientBCCList.size(); i++) {

  212. System.out.println("发送到:" + recipientBCCList.get(i));

  213. sendTo[i] = new InternetAddress(recipientBCCList.get(i), "", "UTF-8");

  214. }

  215. message.addRecipients(MimeMessage.RecipientType.BCC, sendTo);

  216. }

  217. }

  218.  
  219. /***添加附件****/

  220. private void addFile(Multipart multipart) throws MessagingException, UnsupportedEncodingException {

  221. if (filePath.size() == 0)

  222. return;

  223. for (int i = 0; i < filePath.size(); i++) {

  224. MimeBodyPart messageBodyPart = new MimeBodyPart();

  225. // 选择出每一个附件名

  226. String pathName = filePath.get(i);

  227. System.out.println("添加附件 ====>" + pathName);

  228. // 得到数据源

  229. FileDataSource fds = new FileDataSource(pathName);

  230. // 得到附件本身并至入BodyPart

  231. messageBodyPart.setDataHandler(new DataHandler(fds));

  232. //采用这去除中文乱码

  233. messageBodyPart.setFileName(MimeUtility.encodeText(fds.getName()));

  234. multipart.addBodyPart(messageBodyPart);

  235. }

  236. }

  237.  
  238. private boolean sync = true;

  239.  
  240. /**

  241. * 规定设置 传输协议为smtp 根据输入的邮箱地址自动匹配smtp服务器地址与smtp服务器地址端口

  242. */

  243. private void getProperties() {

  244. String account[] = mailAccount.split("@");

  245. String mailTpye = "";

  246. try {

  247. mailTpye = account[1];

  248. } catch (Exception e) {

  249. System.err.println("不正确的邮箱地址!");

  250. sync = false;

  251. return;

  252. }

  253. String SMTPHost = "";//smtp服务器地址

  254. String SMTPPort = "";//smtp服务器地址端口

  255. switch (mailTpye) {

  256. case "qq.com":

  257. case "foxmail.com":

  258. SMTPHost = "smtp.qq.com";

  259. SMTPPort = "465";

  260. break;

  261. case "sina.com":

  262. SMTPHost = "smtp.sina.com";

  263. SMTPPort = "25";

  264. break;

  265. case "sina.cn":

  266. SMTPHost = "smtp.sina.cn";

  267. SMTPPort = "25";

  268. break;

  269. case "139.com":

  270. SMTPHost = "smtp.139.com";

  271. SMTPPort = "465";

  272. break;

  273. case "163.com":

  274. SMTPHost = "smtp.163.com";

  275. SMTPPort = "25";

  276. break;

  277. case "188.com":

  278. SMTPHost = "smtp.188.com";

  279. SMTPPort = "25";

  280. break;

  281. case "126.com":

  282. SMTPHost = "smtp.126.com";

  283. SMTPPort = "25";

  284. break;

  285. case "gmail.com":

  286. SMTPHost = "smtp.gmail.com";

  287. SMTPPort = "465";

  288. break;

  289. case "outlook.com":

  290. SMTPHost = "smtp.outlook.com";

  291. SMTPPort = "465";

  292. break;

  293. default:

  294. System.err.println("暂时不支持此账号作为服务账号发送邮件!");

  295. return;

  296. }

  297. Properties prop = new Properties();

  298. prop.setProperty("mail.transport.protocol", "smtp"); // 设置邮件传输采用的协议smtp

  299. prop.setProperty("mail.smtp.host", SMTPHost);// 设置发送人邮件服务器的smtp地址

  300. prop.setProperty("mail.smtp.auth", "true"); // 设置验证机制

  301. prop.setProperty("mail.smtp.port", SMTPPort);// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,

  302. prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

  303. prop.setProperty("mail.smtp.socketFactory.fallback", "false");

  304. prop.setProperty("mail.smtp.socketFactory.port", SMTPPort);

  305. properties = prop;

  306. session = Session.getInstance(properties);

  307. session.setDebug(debug);

  308. }

  309.  
  310. }

 

 

        完成这些需要导入的重要jar包:mail-1.4.1.jar(或者更高的版本) 和 activation 包,jdk1.8中rt.jar包含的activation 包。所以jdk1.8的就无需考虑activation 怎么下载了。

        完成解析分配服务器地址和端口的主要函数(写的不怎么好):

 
  1. private void getProperties() {

  2. String account[] = mailAccount.split("@");

  3. String mailTpye = "";

  4. try {

  5. mailTpye = account[1];

  6. } catch (Exception e) {

  7. System.err.println("不正确的邮箱地址!");

  8. sync = false;

  9. return;

  10. }

  11. String SMTPHost = "";//smtp服务器地址

  12. String SMTPPort = "";//smtp服务器地址端口

  13. switch (mailTpye) {

  14. case "qq.com":

  15. case "foxmail.com":

  16. SMTPHost = "smtp.qq.com";

  17. SMTPPort = "465";

  18. break;

  19. case "sina.com":

  20. SMTPHost = "smtp.sina.com";

  21. SMTPPort = "25";

  22. break;

  23. case "sina.cn":

  24. SMTPHost = "smtp.sina.cn";

  25. SMTPPort = "25";

  26. break;

  27. case "139.com":

  28. SMTPHost = "smtp.139.com";

  29. SMTPPort = "465";

  30. break;

  31. case "163.com":

  32. SMTPHost = "smtp.163.com";

  33. SMTPPort = "25";

  34. break;

  35. case "188.com":

  36. SMTPHost = "smtp.188.com";

  37. SMTPPort = "25";

  38. break;

  39. case "126.com":

  40. SMTPHost = "smtp.126.com";

  41. SMTPPort = "25";

  42. break;

  43. case "gmail.com":

  44. SMTPHost = "smtp.gmail.com";

  45. SMTPPort = "465";

  46. break;

  47. case "outlook.com":

  48. SMTPHost = "smtp.outlook.com";

  49. SMTPPort = "465";

  50. break;

  51. default:

  52. System.err.println("暂时不支持此账号作为服务账号发送邮件!");

  53. return ;

  54. }

  55. Properties prop = new Properties();

  56. prop.setProperty("mail.transport.protocol", "smtp"); // 设置邮件传输采用的协议smtp

  57. prop.setProperty("mail.smtp.host", SMTPHost);// 设置发送人邮件服务器的smtp地址

  58. prop.setProperty("mail.smtp.auth", "true"); // 设置验证机制

  59. prop.setProperty("mail.smtp.port", SMTPPort);// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加

  60. prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

  61. prop.setProperty("mail.smtp.socketFactory.fallback", "false");

  62. prop.setProperty("mail.smtp.socketFactory.port", SMTPPort);

  63. properties = prop;

  64. session = Session.getInstance(properties);

  65. session.setDebug(debug);

  66. }

最后看看效果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值