邮件发送器

  1. /**
  2. * 邮件发送器
  3. *
  4. * @author Zebe
  5. */
  6. public class MailSender implements Runnable {
  7.  
  8. /**
  9. * 收件人
  10. */
  11. private String to;
  12.  
  13. /**
  14. * 收件人名称
  15. */
  16. private String toName;
  17.  
  18. /**
  19. * 主题
  20. */
  21. private String subject;
  22.  
  23. /**
  24. * 内容
  25. */
  26. private String content;
  27.  
  28. /**
  29. * 附件列表
  30. */
  31. private List<String> attachFileList;
  32.  
  33. /**
  34. * 构造器
  35. * @param to 收件人
  36. * @param subject 主题
  37. * @param content 内容
  38. */
  39. public MailSender(String to,String toName, String subject, String content) {
  40. this.to = to;
  41. this.toName = toName;
  42. this.subject = subject;
  43. this.content = content;
  44. }
  45.  
  46. /**
  47. * 构造器
  48. * @param to 收件人
  49. * @param subject 主题
  50. * @param content 内容
  51. * @param attachFileList 附件列表
  52. */
  53. public MailSender(String to, String toName,String subject, String content, List<String> attachFileList) {
  54. this(to, toName, subject, content);
  55. this.attachFileList = attachFileList;
  56. }
  57.  
  58. @Override
  59. public void run() {
  60. new SendEmailUtil(to,toName, subject, content, attachFileList).send();
  61. }
  62.  
  63. }

邮件发送线程池

  1. /**
  2. * 邮件发送线程池
  3. *
  4. * @author Zebe
  5. */
  6. public class MailSenderPool {
  7.  
  8. /**
  9. * 邮件发送器线程数量
  10. */
  11. private static int SENDER_TOTAL = 10;
  12.  
  13. /**
  14. * 线程工厂(生产环境中建议使用带命名参数的线程工厂)
  15. */
  16. private static ThreadFactory threadFactory = Executors.defaultThreadFactory();
  17.  
  18. /**
  19. * 线程池执行器(采用了Spring提供的CustomizableThreadFactory,如果不需要请使用默认线程工厂)
  20. */
  21. private static ExecutorService executor = new ThreadPoolExecutor(SENDER_TOTAL, 200,
  22. 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), threadFactory,
  23. new ThreadPoolExecutor.AbortPolicy());
  24.  
  25. /**
  26. * 内部静态实例
  27. */
  28. private static class Inner {
  29. private static MailSenderPool instance = new MailSenderPool();
  30. }
  31.  
  32. /**
  33. * 获取实例
  34. *
  35. * @return 返回邮件发送线程池实例
  36. */
  37. public static MailSenderPool getInstance() {
  38. return Inner.instance;
  39. }
  40.  
  41. /**
  42. * 通过线程发送
  43. *
  44. * @param sender 邮件发送器
  45. * @return 返回自身
  46. */
  47. public MailSenderPool sendByThread(MailSender sender) {
  48. executor.execute(sender);
  49. return getInstance();
  50. }
  51.  
  52. /**
  53. * 关闭线程池
  54. */
  55. public void shutDown() {
  56. executor.shutdown();
  57. }
  58.  
  59. }

邮件发送工具类

  1. /**
  2. * 邮件发送工具类。
  3. * 以下邮件中的配置参数,请在实际环境中,根据需要采取合适的配置方式。
  4. * 发送邮件依赖 com.sun.mail(1.6.1) 包、javax.mail(1.5.0-b01) 包。
  5. * 如果使用 Idea 运行,请将这两个包(可以直接到Maven目录下面去找)添加到项目的 Libraries 里面(快捷键:Ctrl + Alt + Shift + S)
  6. *
  7. * @author Zebe
  8. */
  9. public class SendEmailUtil {
  10.  
  11. /**
  12. * 发件人别名(可以为空)
  13. */
  14. private final static String fromAliasName = "****";
  15.  
  16. /**
  17. * 登录用户名
  18. */
  19. private String ACCOUNT;
  20.  
  21. /**
  22. * 登录密码
  23. */
  24. private String PASSWORD;
  25.  
  26. /**
  27. * 邮件服务器地址
  28. */
  29. //QQ企业邮箱:smtp.exmail.qq.com
  30. //网易企业邮箱:smtphz.qiye.163.com
  31. private String HOST;
  32.  
  33. /**
  34. * 发信端口
  35. */
  36. //QQ企业邮箱:465
  37. //网易企业邮箱:994
  38. private String PORT;
  39.  
  40. /**
  41. * 发信协议
  42. */
  43. private final static String PROTOCOL = "ssl";
  44.  
  45. /**
  46. * 收件人
  47. */
  48. private String to;
  49.  
  50. /**
  51. * 收件人名称
  52. */
  53. private String toName;
  54.  
  55. /**
  56. * 主题
  57. */
  58. private String subject;
  59.  
  60. /**
  61. * 内容
  62. */
  63. private String content;
  64.  
  65. /**
  66. * 附件列表(可以为空)
  67. */
  68. private List<String> attachFileList;
  69.  
  70. /**
  71. * 构造器
  72. *
  73. * @param attachFileList 附件列表
  74. */
  75. public SendEmailUtil(MailTemplate mailTemplate, List<String> attachFileList) {
  76. this.to = mailTemplate.getTo();
  77. this.toName = mailTemplate.getToName();
  78. this.subject = mailTemplate.getSubject();
  79. this.content = mailTemplate.getContent();
  80. this.attachFileList = attachFileList;
  81. this.ACCOUNT = mailTemplate.getAccount();
  82. this.PASSWORD = mailTemplate.getPassword();
  83. switch (mailTemplate.getSendType()) {
  84. case "qq":
  85. this.HOST = "smtp.exmail.qq.com";
  86. this.PORT = "465";
  87. break;
  88. case "163":
  89. this.HOST = "smtp.ym.163.com";
  90. this.PORT = "994";
  91. break;
  92. }
  93. }
  94.  
  95. /**
  96. * 认证信息
  97. */
  98. static class MyAuthenticator extends Authenticator {
  99.  
  100. /**
  101. * 用户名
  102. */
  103. String username = null;
  104.  
  105. /**
  106. * 密码
  107. */
  108. String password = null;
  109.  
  110. /**
  111. * 构造器
  112. *
  113. * @param username 用户名
  114. * @param password 密码
  115. */
  116. public MyAuthenticator(String username, String password) {
  117. this.username = username;
  118. this.password = password;
  119. }
  120.  
  121. @Override
  122. protected PasswordAuthentication getPasswordAuthentication() {
  123. return new PasswordAuthentication(username, password);
  124. }
  125. }
  126.  
  127. /**
  128. * 发送邮件
  129. */
  130. public boolean send() {
  131. // 设置邮件属性
  132. Properties prop = new Properties();
  133. prop.setProperty("mail.transport.protocol", PROTOCOL);
  134. prop.setProperty("mail.smtp.host", HOST);
  135. prop.setProperty("mail.smtp.port", PORT);
  136. prop.setProperty("mail.smtp.auth", "true");
  137. MailSSLSocketFactory sslSocketFactory = null;
  138. try {
  139. sslSocketFactory = new MailSSLSocketFactory();
  140. sslSocketFactory.setTrustAllHosts(true);
  141. } catch (GeneralSecurityException e1) {
  142. e1.printStackTrace();
  143. }
  144. if (sslSocketFactory == null) {
  145. System.err.println("开启 MailSSLSocketFactory 失败");
  146. } else {
  147. prop.put("mail.smtp.ssl.enable", "true");
  148. prop.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
  149. // 创建邮件会话(注意,如果要在一个进程中切换多个邮箱账号发信,应该用 Session.getInstance)
  150. Session session = Session.getDefaultInstance(prop, new MyAuthenticator(ACCOUNT, PASSWORD));
  151. // 开启调试模式(生产环境中请不要开启此项)
  152. session.setDebug(true);
  153. try {
  154. MimeMessage mimeMessage = new MimeMessage(session);
  155. // 设置发件人别名(如果未设置别名就默认为发件人邮箱)
  156. mimeMessage.setFrom(new InternetAddress(ACCOUNT, fromAliasName));
  157. // 设置主题和收件人、发信时间等信息
  158. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to, toName));
  159. mimeMessage.setSubject(subject);
  160. mimeMessage.setSentDate(new Date());
  161.  
  162. //图片
  163. MimeBodyPart img = new MimeBodyPart();
  164. DataHandler dh = new DataHandler(new FileDataSource("src/main/resources/2.jpg"));//图片路径
  165. img.setDataHandler(dh);
  166. img.setContentID("img");
  167. //正文
  168. MimeBodyPart text = new MimeBodyPart();
  169. text.setContent("这里正文内容 for img<img src='cid:img'><br/>", "text/html;charset=utf-8"); //注意编码问题
  170.  
  171. //描述数据关系
  172. MimeMultipart mm = new MimeMultipart();
  173. mm.addBodyPart(text);
  174. mm.addBodyPart(img);
  175. mm.setSubType("related");
  176.  
  177. //图片-文本--复合--转普通节点
  178. MimeBodyPart tex_image_tPart=new MimeBodyPart();
  179. tex_image_tPart.setContent(mm);
  180.  
  181. // 如果有附件信息,则添加附件
  182. if (!attachFileList.isEmpty()) {
  183. Multipart multipart = new MimeMultipart();
  184. MimeBodyPart body = new MimeBodyPart();
  185. body.setContent(content, "text/html; charset=UTF-8");
  186. multipart.addBodyPart(body);
  187. // 添加所有附件(添加时判断文件是否存在)
  188. for (String filePath : attachFileList) {
  189. if (Files.exists(Paths.get(filePath))) {
  190. MimeBodyPart tempBodyPart = new MimeBodyPart();
  191. tempBodyPart.attachFile(filePath);
  192. multipart.addBodyPart(tempBodyPart);
  193. }
  194. }
  195. mimeMessage.setContent(multipart);
  196. } else {
  197. // Multipart multipart = new MimeMultipart();
  198. // MimeBodyPart body = new MimeBodyPart();
  199. // body.setContent(mm, "text/html; charset=UTF-8");
  200. // multipart.addBodyPart(body);
  201. MimeMultipart mimeMultipart1=new MimeMultipart();
  202. mimeMultipart1.addBodyPart(tex_image_tPart);
  203. mimeMultipart1.setSubType("mixd");//混合关系
  204. mimeMessage.setContent(mimeMultipart1, "text/html; charset=UTF-8");
  205. //mimeMessage.setText(content);
  206. }
  207. // 开始发信
  208. mimeMessage.saveChanges();
  209. Transport.send(mimeMessage);
  210. return true;
  211. } catch (MessagingException | IOException e) {
  212. e.printStackTrace();
  213. return false;
  214. }
  215. }
  216. return false;
  217. }
  218. }

示例

  1. public static void main(String[] args) {
  2. try {
  3. int num;
  4. // 通过线程池发送邮件
  5. MailSenderPool pool = MailSenderPool.getInstance();
  6. for (num=1;num<=73;num++){
  7. // 设置发信参数
  8. final String toName = "我是" + num + "号";
  9. final String to = "test" + num + "@***.com";
  10. String subject = num + " 第一次发送测试邮件标题";
  11. final String content = "<p style='color:red'>这是邮件内容正文。</p>";
  12. // 设置附件路径(注意:res 是项目根目录下的一个文件夹)
  13. // final List<String> attachFileList = Arrays.asList("res/1.png", "res/1.pdf");
  14. pool.sendByThread(new MailSender(to,toName, subject, content, new ArrayList<>()));
  15. subject = num + " 第二次发送测试邮件标题";
  16. pool.sendByThread(new MailSender(to,toName, subject, content, new ArrayList<>()));
  17. }
  18. pool.shutDown();
  19. }catch (Exception e){
  20. System.out.println("错误: " + e);
  21. }
  22. }
  1.  

【Java】JavaMail使用网易企业邮箱发邮件的更多相关文章

  1. C# 用QQ企业邮箱发邮件

    问题System.Net.Mail下的SmtpClient来发送邮件,而System.Net.Mail only仅支持Explicit SSL 不要465端口,用25,不用EnableSsl = tr ...

  2. Java实现网易企业邮箱发送邮件

    最近项目需要用网易企业邮箱发送邮件,特意来将实现过程记录一下: maven导入jar包 <!-- javax.mai 核心包 --> <dependency> <grou ...

  3. Apache Commons Email 使用网易企业邮箱发送邮件

    最近使用HtmlEmail 发送邮件,使用网易企业邮箱,发送邮件,死活发不出去!原以为是网易企业邮箱,不支持发送邮箱,后面经过研究发现,是apache htmlEmail 的协议导致,apache E ...

  4. win10自带邮箱添加网易企业邮箱

    开始-邮件-账户-添加账户-高级安装程序-internet电子邮件-然后输入网易企业邮箱的用户名和相关服务器设置就行了 接收服务器 pop.qiye.163.com发送服务器 smtp.qiye.16 ...

  5. MVC4/5+jquery+bootstrap样式+dataTables+linq+WCF+EF6后台和前台的框架集合!好蛋疼哦!数据库支持MYSQL 和MSSQL,oracle。集成腾讯企业邮箱收邮件同步用户SSO登陆等功能。

    花费了我好多心血,才做出来,下个项目准备用这个框架! 大家有没有做这方面的可以交流一下! 花费了我好多心血,才做出来,下个项目准备用这个框架! 大家有没有做这方面的可以交流一下! 花费了我好多心血,才 ...

  6. python webdriver 登录163邮箱发邮件加附件, 外加数据和程序分离,配置文件的方式

    配置文件:UiObjectMapSendMap.ini用来存放配置信息 GetOptionSendMail.py 用来读取配信息 #encoding=utf-8from selenium.webdri ...

  7. Foxmail登录不了网易企业邮箱解决办法

    关于Foxmail登录不了网易企业邮箱问题 解决办法是:在设置账号的时候手动设置pop服务器和smtp服务器. 新建账号的图: 点击“手动设置”出现如下界面: 设置完成后问题解决.下面的两个是正确的, ...

  8. mailx加163邮箱发邮件

    mailx加163邮箱发邮件 参考:https://www.cnblogs.com/myvic/p/9579954.html 配置 $ yum install mailx -y $ vim /etc/ ...

  9. javamail腾讯企业邮箱发送邮件

    此代码用的jar文件:mail.jar(1.4.5版本); 如果jdk用的是1.8版本会出现SSL错误:这个问题是jdk导致的,jdk1.8里面有一个jce的包,安全性机制导致的访问https会报错, ...

随机推荐

  1. 一次性计划任务at与周期性计划任务crontab

    一.at一次性计划任务使用 at语法格式: at 时间 at设置计划任务 1.下载at程序 [root@li ~]# yum install at -y 2.启动atd服务 [root@li ~]# ...

  2. [Git] 014 远程仓库篇 第一话

    0. 前言 在 [Git] 001 初识 Git 与 GitHub 之新建仓库 中,我在 GitHub 上建了一个仓库 "interesting" 这回的任务 把远程的 " ...

  3. 【嵌入式 Linux文件系统】如何使用Initramfs文件系统

    (1)#cd ../rootfs/ #ln -s ./bin/busybox init 创建软链接 (2)进入Linux内核 #make menuconfig General setup-->I ...

  4. @-webkit-keyframes 动画 css3

    Internet Explorer 10.Firefox 以及 Opera 支持 @keyframes 规则和 animation 属性. Chrome 和 Safari 需要前缀 -webkit-. ...

  5. Java语言的发展历程

    前言 自1946年2月14日世界上首款计算机ENAC问世,第一代计算机语言“机器语言”便诞生了,它使用的是最原始的穿孔卡片,这种卡片上使用的语言只有专家才能理解,与人类语言差别极大.这种语言本质上是计 ...

  6. Qt 遍历不规则树的节点

    在使用Qt的GraphicsScene作图时,遇到类似这样的需求:在scene中创建节点类似下图, 现在我要把每个节点的txt保存到xml文件中,结构为 <?xml version='1.0' ...

  7. Python webdriver调用Chrome报错

    报错信息如下: selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to b ...

  8. CSS选择符有哪些?哪些属性可以继承

    下面是一些常用的选择器: 1.id选择器( # myid) 2.类选择器(.myclassname) 3.标签选择器(div, h1, p) 4.相邻选择器(h1 + p) 5.子选择器(ul > ...

  9. Docker介绍,安装和常用的命令

    Docker是Google公司推出的Go语言开发的,基于Linux内核的cgroup,namespace,AUFS类的UnionFS等技术.对进程进行封装格力,属于操作系统层面的虚拟化技术.隔离的进程 ...

  10. 洛谷 P2704 [NOI2001]炮兵阵地 (状态压缩DP+优化)

    题目描述 司令部的将军们打算在NM的网格地图上部署他们的炮兵部队.一个NM的地图由N行M列组成,地图的每一格可能是山地(用"H" 表示),也可能是平原(用"P" ...