亲宝软件园·资讯

展开

使用Java-mail 发送邮件

Amour恋空 人气:0

首先:

我们准备工作需要准备 

jar包   mail.jar

POP3/SMTP服务  以qq为例

发送邮箱的账号  *********.@qq.com

发送邮箱授权码  获取流程如下

进入邮箱,点击设置

 

 

 

拉到最后,将POP3服务开启

之后生成授权码

 

获取授权码 

这样 准备工作基本完成就可以写代码了

这是自己写的一个工具类,注释也加上了,虽然自带debug信息,但是那个比较多,所以在每个方法中打印输出了一下,默认使用的是qq的邮箱,更改至于要修改相应位置的属性就行

 
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Properties;
  11. import javax.activation.DataHandler;
  12. import javax.activation.DataSource;
  13. import javax.activation.FileDataSource;
  14. import javax.mail.Address;
  15. import javax.mail.Authenticator;
  16. import javax.mail.BodyPart;
  17. import javax.mail.Message;
  18. import javax.mail.MessagingException;
  19. import javax.mail.Multipart;
  20. import javax.mail.PasswordAuthentication;
  21. import javax.mail.Session;
  22. import javax.mail.Transport;
  23. import javax.mail.internet.AddressException;
  24. import javax.mail.internet.InternetAddress;
  25. import javax.mail.internet.MimeBodyPart;
  26. import javax.mail.internet.MimeMessage;
  27. import javax.mail.internet.MimeMultipart;
  28. import javax.mail.internet.MimeUtility;
  29. /**
  30. *
  31. * 项目名称:JavaMail
  32. * 类名称:SendMail
  33. * 类描述:
  34. * 创建人:Ai
  35. * 创建时间:2018年5月2日 下午3:49:45
  36. * 修改人:Ai
  37. * 修改时间:2018年5月2日 下午3:49:45
  38. * 修改备注:javaMail封装代码
  39. * @version JM-0.1
  40. *
  41. */
  42. public class SendMail {
  43. private final String username = "*****@qq.com"; //发送邮件的邮箱
  44. private final String password = "*********";   //发送邮箱的授权码
  45. private Authenticator auth = null;
  46. private MimeMessage mimeMessage = null;
  47. private Properties pros = null;
  48. private Multipart multipart = null;
  49. private BodyPart bodypart = null;
  50. /**
  51. * 初始化账号密码并验证 创建MimeMessage对象 发送邮件必须的步骤:1
  52. *
  53. * @param username
  54. * @param password
  55. */
  56. public SendMail() {
  57. Map<String, String> map = new HashMap<String, String>();
  58. // 你的发送邮箱账号 POP3/SMTP服务 授权码
  59. map.put("mail.smtp.host", "smtp.qq.com");
  60. map.put("mail.smtp.auth", "true");
  61. map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  62. map.put("mail.smtp.port", "465");
  63. map.put("mail.smtp.socketFactory.port", "465");
  64. setPros(map);
  65. initMessage();
  66. }
  67. /**
  68. * 设置email系统参数 接收一个map集合key为string类型,值为String 发送邮件必须的步骤:2
  69. *
  70. * @param map
  71. */
  72. public boolean setPros(Map<String, String> map) {
  73. pros = new Properties();
  74. try {
  75. for (Map.Entry<String, String> entry : map.entrySet()) {
  76. pros.setProperty(entry.getKey(), entry.getValue());
  77. }
  78. System.out.println("设置email参数成功!");
  79. return true;
  80. } catch (Exception e) {
  81. return false;
  82. }
  83. }
  84. /**
  85. * 初始化MimeMessage对象 发送邮件必须的步骤:3
  86. */
  87. public boolean initMessage() {
  88. this.auth = new Email_Autherticator();
  89. try {
  90. Session session = Session.getDefaultInstance(pros, auth);
  91. session.setDebug(false); // 设置获取 debug 信息
  92. mimeMessage = new MimeMessage(session);
  93. System.out.println("初始化成功!");
  94. return true;
  95. } catch (Exception e) {
  96. return false;
  97. }
  98. }
  99. /**
  100. * 验证账号密码 发送邮件必须的步骤
  101. *
  102. * @author Administrator
  103. *
  104. */
  105. public class Email_Autherticator extends Authenticator {
  106. public PasswordAuthentication getPasswordAuthentication() {
  107. return new PasswordAuthentication(username, password);
  108. }
  109. }
  110. /**
  111. * 设置发送邮件的基本参数(去除繁琐的邮件设置)
  112. *
  113. * @param sub
  114. * 设置邮件主题
  115. * @param text
  116. * 设置邮件文本内容
  117. * @param rec
  118. * 设置邮件接收人
  119. * @throws MessagingException
  120. * @throws UnsupportedEncodingException
  121. */
  122. public boolean setDefaultMessagePros(String sub, String text, String rec)
  123. throws MessagingException, UnsupportedEncodingException {
  124. try {
  125. mimeMessage.setSubject(sub);
  126. mimeMessage.setText(text);
  127. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
  128. mimeMessage.setSentDate(new Date());
  129. mimeMessage.setFrom(new InternetAddress(username, username));
  130. System.out.println("设置邮件发送基本参数成功!(主题、内容、接收人)");
  131. return true;
  132. } catch (Exception e) {
  133. return false;
  134. }
  135. }
  136. /**
  137. * 设置主题
  138. *
  139. * @param subject
  140. * @throws MessagingException
  141. */
  142. public boolean setSubject(String subject) throws MessagingException {
  143. try {
  144. mimeMessage.setSubject(subject);
  145. System.out.println("设置邮件主题[" + subject + "]成功!");
  146. return true;
  147. } catch (Exception e) {
  148. return false;
  149. }
  150. }
  151. /**
  152. * 设置日期
  153. *
  154. * @param date
  155. * 邮件发送的日期
  156. * @throws MessagingException
  157. */
  158. public boolean setDate(Date date) throws MessagingException {
  159. try {
  160. mimeMessage.setSentDate(date);
  161. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  162. String format = sdf.format(date);
  163. System.out.println("设置邮件发送日期[" + format + "]成功!");
  164. return true;
  165. } catch (Exception e) {
  166. return false;
  167. }
  168. }
  169. /**
  170. * 设置日期
  171. *
  172. * @param millisecond
  173. * 邮件延时发送时间(毫秒) //暂不好使
  174. * @throws MessagingException
  175. */
  176. public boolean setDate(long millisecond) throws MessagingException {
  177. Date date = new Date();
  178. System.out.println(date);
  179. date.setTime(date.getTime() + millisecond);
  180. try {
  181. mimeMessage.setSentDate(date);
  182. System.out.println("设置邮件发送延时[" + millisecond + "]毫秒成功!");
  183. } catch (Exception e) {
  184. System.out.println("设置邮件发送日期[" + millisecond + "]失败!");
  185. return false;
  186. }
  187. return true;
  188. }
  189. /**
  190. * 设置邮件接收人地址 <单人发送>
  191. *
  192. * @param recipient
  193. * @throws MessagingException
  194. */
  195. public boolean setRecipient(String recipient) throws MessagingException {
  196. try {
  197. if (recipient.isEmpty()) {
  198. System.out.println("接收人地址为空!");
  199. return false;
  200. } else {
  201. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
  202. System.out.println("设置接收人地址为[" + recipient + "]成功!");
  203. return true;
  204. }
  205. } catch (Exception e) {
  206. return false;
  207. }
  208. }
  209. /**
  210. * 设置邮件接收人地址 <多人发送>
  211. *
  212. * @param list
  213. * @throws MessagingException
  214. * @throws AddressException
  215. */
  216. public boolean setRecipients(List<String> recs) throws AddressException, MessagingException {
  217. try {
  218. if (recs.isEmpty()) {
  219. System.out.println("接收人地址为空!");
  220. return false;
  221. }
  222. for (String str : recs) {
  223. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
  224. }
  225. System.out.println("设置接收人地址" + recs + "成功!");
  226. return true;
  227. } catch (Exception e) {
  228. return false;
  229. }
  230. }
  231. /**
  232. * 设置邮件接收人地址 <多人发送>
  233. *
  234. * @param StringBuffer<parms,parms2,parms.....>
  235. * @throws MessagingException
  236. * @throws AddressException
  237. */
  238. @SuppressWarnings("static-access")
  239. public boolean setRecipients(StringBuffer sb) throws AddressException, MessagingException {
  240. try {
  241. if (sb == null || "".equals(sb)) {
  242. System.out.println("字符串数据为空!");
  243. return false;
  244. }
  245. Address[] address = new InternetAddress().parse(sb.toString());
  246. mimeMessage.addRecipients(Message.RecipientType.TO, address);
  247. System.out.println("设置接收人地址[" + sb + "]成功!");
  248. return true;
  249. } catch (Exception e) {
  250. return false;
  251. }
  252. }
  253. /**
  254. * 设置邮件发送人的名字
  255. *
  256. * @param from
  257. * @throws UnsupportedEncodingException
  258. * @throws MessagingException
  259. */
  260. public boolean setFrom(String from) throws UnsupportedEncodingException, MessagingException {
  261. try {
  262. if (from.isEmpty()) {
  263. System.out.println("邮件发送人名字为空!");
  264. return false;
  265. } else {
  266. mimeMessage.setFrom(new InternetAddress(username, from));
  267. System.out.println("设置邮件发送人名字[" + from + "]成功!");
  268. return true;
  269. }
  270. } catch (Exception e) {
  271. return false;
  272. }
  273. }
  274. /**
  275. * 发送邮件<单人发送> return 是否发送成功
  276. *
  277. * @throws MessagingException
  278. * 发送异常
  279. */
  280. public boolean sendMessage() {
  281. try {
  282. Transport.send(mimeMessage);
  283. System.out.println("----------------发送成功----------------");
  284. return true;
  285. } catch (MessagingException e) {
  286. return false;
  287. }
  288. }
  289. /**
  290. * 设置附件
  291. *
  292. * @param file
  293. * 发送文件的路径
  294. * @throws MessagingException
  295. * 发送异常
  296. * @throws IOException
  297. * 文件IO异常
  298. *
  299. */
  300. public boolean setMultipart(String file) throws MessagingException, IOException {
  301. try {
  302. if (multipart == null) {
  303. multipart = new MimeMultipart();
  304. }
  305. multipart.addBodyPart(writeFiles(file));
  306. mimeMessage.setContent(multipart);
  307. System.out.println("设置邮件附件" + file + "成功!");
  308. return true;
  309. } catch (Exception e) {
  310. return false;
  311. }
  312. }
  313. /**
  314. * 设置附件<添加多附件>
  315. *
  316. * @param fileList<接收List集合>
  317. * @throws MessagingException
  318. * 发送异常
  319. * @throws IOException
  320. * 文件IO异常
  321. */
  322. public boolean setMultiparts(List<String> fileList) throws MessagingException, IOException {
  323. try {
  324. if (multipart == null) {
  325. multipart = new MimeMultipart();
  326. }
  327. for (String s : fileList) {
  328. multipart.addBodyPart(writeFiles(s));
  329. }
  330. mimeMessage.setContent(multipart);
  331. System.out.println("设置邮件附件" + fileList + "成功!");
  332. return true;
  333. } catch (Exception e) {
  334. return false;
  335. }
  336. }
  337. /**
  338. * 发送文本内容,设置编码方式 <方法与发送附件配套使用> <发送普通的文本内容请使用setText()方法>
  339. *
  340. * @param s
  341. * 发送的文本内容
  342. * @param type
  343. * 编码格式
  344. * @throws MessagingException
  345. */
  346. public boolean setContent(String s, String type) throws MessagingException {
  347. try {
  348. if (multipart == null) {
  349. multipart = new MimeMultipart();
  350. }
  351. bodypart = new MimeBodyPart();
  352. bodypart.setContent(s, type);
  353. multipart.addBodyPart(bodypart);
  354. mimeMessage.setContent(multipart);
  355. mimeMessage.saveChanges();
  356. System.out.println("设置邮件内容[" + s + "]成功!");
  357. return true;
  358. } catch (Exception e) {
  359. return false;
  360. }
  361. }
  362. /**
  363. * 读取附件
  364. *
  365. * @param filePath
  366. * 文件路径
  367. * @return
  368. * @throws IOException
  369. * @throws MessagingException
  370. */
  371. public BodyPart writeFiles(String filePath) throws IOException, MessagingException {
  372. File file = new File(filePath);
  373. if (!file.exists()) {
  374. throw new IOException("文件不存在!请确定文件路径是否正确");
  375. }
  376. bodypart = new MimeBodyPart();
  377. DataSource dataSource = new FileDataSource(file);
  378. bodypart.setDataHandler(new DataHandler(dataSource));
  379. // 文件名要加入编码,不然出现乱码
  380. bodypart.setFileName(MimeUtility.encodeText(file.getName()));
  381. return bodypart;
  382. }
  383. //----------------------------------------------------------------------------------------------------------------------------
  384. public static void main(String[] args) throws MessagingException, IOException {
  385. SendMail mail = new SendMail();
  386. /*
  387. * 调用setRecipients(list);发送list集合类型 List<String> list = new
  388. * ArrayList<String>(); list.add("********@qq.com");
  389. */
  390. List<String> list = new ArrayList<String>();
  391. list.add("45244445@qq.com");
  392. mail.setRecipients(list); // 输出信息
  393. // 邮件主题
  394. mail.setSubject("AI测试Java邮箱功能");
  395. // 发送时间 Date类型(默认即时发送)
  396. mail.setDate(new Date());
  397. //mail.setDate(100);
  398. // 发送者昵称
  399. mail.setFrom("AI");
  400. // 邮件内容
  401. mail.setContent("你的验证码为:<a>fds</a>", "text/html; charset=UTF-8");
  402. // 附件集合
  403. List<String> fileList = new ArrayList<String>();
  404. // 添加附件
  405. fileList.add("D:1.jpg");
  406. mail.setMultiparts(fileList);
  407. mail.sendMessage(); // 是否发送成功
  408. }
  409. }

我将代码整理了一下封装了简单的发生方法

  1. package com.yunhe.day1023;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Properties;
  12. import javax.activation.DataHandler;
  13. import javax.activation.DataSource;
  14. import javax.activation.FileDataSource;
  15. import javax.mail.Address;
  16. import javax.mail.Authenticator;
  17. import javax.mail.BodyPart;
  18. import javax.mail.Message;
  19. import javax.mail.MessagingException;
  20. import javax.mail.Multipart;
  21. import javax.mail.PasswordAuthentication;
  22. import javax.mail.Session;
  23. import javax.mail.Transport;
  24. import javax.mail.internet.AddressException;
  25. import javax.mail.internet.InternetAddress;
  26. import javax.mail.internet.MimeBodyPart;
  27. import javax.mail.internet.MimeMessage;
  28. import javax.mail.internet.MimeMultipart;
  29. import javax.mail.internet.MimeUtility;
  30. /**
  31. *
  32. * 项目名称:JavaMail 类名称:SendMail 类描述: 创建人:Ai 创建时间:2018年5月2日 下午3:49:45 修改人:Ai
  33. * 修改时间:2018年5月2日 下午3:49:45 修改备注:javaMail封装代码
  34. *
  35. * @version JM-0.1
  36. *
  37. */
  38. /**
  39. * @author Administrator
  40. *
  41. */
  42. /**
  43. * @author Administrator
  44. *
  45. */
  46. public class SendMail {
  47. private final String username = ""; // 发送邮件的邮箱
  48. private final String password = "";// 发送邮箱的授权码
  49. private Authenticator auth = null;
  50. private MimeMessage mimeMessage = null;
  51. private Properties pros = null;
  52. private Multipart multipart = null;
  53. private BodyPart bodypart = null;
  54. /**
  55. * 初始化账号密码并验证 创建MimeMessage对象 发送邮件必须的步骤:1
  56. *
  57. * @param username
  58. * @param password
  59. */
  60. public SendMail() {
  61. Map<String, String> map = new HashMap<String, String>();
  62. // 你的发送邮箱账号 POP3/SMTP服务 授权码
  63. map.put("mail.smtp.host", "smtp.qq.com");
  64. map.put("mail.smtp.auth", "true");
  65. map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  66. map.put("mail.smtp.port", "465");
  67. map.put("mail.smtp.socketFactory.port", "465");
  68. setPros(map);
  69. initMessage();
  70. }
  71. /**
  72. * 设置email系统参数 接收一个map集合key为string类型,值为String 发送邮件必须的步骤:2
  73. *
  74. * @param map
  75. */
  76. public boolean setPros(Map<String, String> map) {
  77. pros = new Properties();
  78. try {
  79. for (Map.Entry<String, String> entry : map.entrySet()) {
  80. pros.setProperty(entry.getKey(), entry.getValue());
  81. }
  82. //System.out.println("设置email参数成功!");
  83. return true;
  84. } catch (Exception e) {
  85. return false;
  86. }
  87. }
  88. /**
  89. * 初始化MimeMessage对象 发送邮件必须的步骤:3
  90. */
  91. public boolean initMessage() {
  92. this.auth = new Email_Autherticator();
  93. try {
  94. Session session = Session.getDefaultInstance(pros, auth);
  95. session.setDebug(false); // 设置获取 debug 信息
  96. mimeMessage = new MimeMessage(session);
  97. //System.out.println("初始化成功!");
  98. return true;
  99. } catch (Exception e) {
  100. return false;
  101. }
  102. }
  103. /**
  104. * 验证账号密码 发送邮件必须的步骤
  105. *
  106. * @author Administrator
  107. *
  108. */
  109. public class Email_Autherticator extends Authenticator {
  110. public PasswordAuthentication getPasswordAuthentication() {
  111. return new PasswordAuthentication(username, password);
  112. }
  113. }
  114. /**
  115. * 设置发送邮件的基本参数(去除繁琐的邮件设置)
  116. *
  117. * @param sub
  118. * 设置邮件主题
  119. * @param text
  120. * 设置邮件文本内容
  121. * @param rec
  122. * 设置邮件接收人
  123. * @throws MessagingException
  124. * @throws UnsupportedEncodingException
  125. */
  126. public boolean setDefaultMessagePros(String sub, String text, String rec)
  127. throws MessagingException, UnsupportedEncodingException {
  128. try {
  129. mimeMessage.setSubject(sub);
  130. mimeMessage.setText(text);
  131. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
  132. mimeMessage.setSentDate(new Date());
  133. mimeMessage.setFrom(new InternetAddress(username, username));
  134. //System.out.println("设置邮件发送基本参数成功!(主题、内容、接收人)");
  135. return true;
  136. } catch (Exception e) {
  137. return false;
  138. }
  139. }
  140. /**
  141. * 设置主题
  142. *
  143. * @param subject
  144. * @throws MessagingException
  145. */
  146. public boolean setSubject(String subject) throws MessagingException {
  147. try {
  148. mimeMessage.setSubject(subject);
  149. //System.out.println("设置邮件主题[" + subject + "]成功!");
  150. return true;
  151. } catch (Exception e) {
  152. return false;
  153. }
  154. }
  155. /**
  156. * 设置日期
  157. *
  158. * @param date
  159. * 邮件发送的日期
  160. * @throws MessagingException
  161. */
  162. public boolean setDate(Date date) throws MessagingException {
  163. try {
  164. mimeMessage.setSentDate(date);
  165. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  166. String format = sdf.format(date);
  167. //System.out.println("设置邮件发送日期[" + format + "]成功!");
  168. return true;
  169. } catch (Exception e) {
  170. return false;
  171. }
  172. }
  173. /**
  174. * 设置日期
  175. *
  176. * @param millisecond
  177. * 邮件延时发送时间(毫秒) //暂不好使
  178. * @throws MessagingException
  179. */
  180. public boolean setDate(long millisecond) throws MessagingException {
  181. Date date = new Date();
  182. //System.out.println(date);
  183. date.setTime(date.getTime() + millisecond);
  184. try {
  185. mimeMessage.setSentDate(date);
  186. //System.out.println("设置邮件发送延时[" + millisecond + "]毫秒成功!");
  187. } catch (Exception e) {
  188. //System.out.println("设置邮件发送日期[" + millisecond + "]失败!");
  189. return false;
  190. }
  191. return true;
  192. }
  193. /**
  194. * 设置邮件接收人地址 <单人发送>
  195. *
  196. * @param recipient
  197. * @throws MessagingException
  198. */
  199. public boolean setRecipient(String recipient) throws MessagingException {
  200. try {
  201. if (recipient.isEmpty()) {
  202. //System.out.println("接收人地址为空!");
  203. return false;
  204. } else {
  205. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
  206. //System.out.println("设置接收人地址为[" + recipient + "]成功!");
  207. return true;
  208. }
  209. } catch (Exception e) {
  210. return false;
  211. }
  212. }
  213. /**
  214. * 设置邮件接收人地址 <多人发送>
  215. *
  216. * @param list
  217. * @throws MessagingException
  218. * @throws AddressException
  219. */
  220. public boolean setRecipients(List<String> recs) throws AddressException, MessagingException {
  221. try {
  222. if (recs.isEmpty()) {
  223. //System.out.println("接收人地址为空!");
  224. return false;
  225. }
  226. for (String str : recs) {
  227. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
  228. }
  229. //System.out.println("设置接收人地址" + recs + "成功!");
  230. return true;
  231. } catch (Exception e) {
  232. return false;
  233. }
  234. }
  235. /**
  236. * 设置邮件接收人地址 <多人发送>
  237. *
  238. * @param StringBuffer<parms,parms2,parms.....>
  239. * @throws MessagingException
  240. * @throws AddressException
  241. */
  242. @SuppressWarnings("static-access")
  243. public boolean setRecipients(StringBuffer sb) throws AddressException, MessagingException {
  244. try {
  245. if (sb == null || "".equals(sb)) {
  246. //System.out.println("字符串数据为空!");
  247. return false;
  248. }
  249. Address[] address = new InternetAddress().parse(sb.toString());
  250. mimeMessage.addRecipients(Message.RecipientType.TO, address);
  251. //System.out.println("设置接收人地址[" + sb + "]成功!");
  252. return true;
  253. } catch (Exception e) {
  254. return false;
  255. }
  256. }
  257. /**
  258. * 设置邮件发送人的名字
  259. *
  260. * @param from
  261. * @throws UnsupportedEncodingException
  262. * @throws MessagingException
  263. */
  264. public boolean setFrom(String from) throws UnsupportedEncodingException, MessagingException {
  265. try {
  266. if (from.isEmpty()) {
  267. //System.out.println("邮件发送人名字为空!");
  268. return false;
  269. } else {
  270. mimeMessage.setFrom(new InternetAddress(username, from));
  271. //System.out.println("设置邮件发送人名字[" + from + "]成功!");
  272. return true;
  273. }
  274. } catch (Exception e) {
  275. return false;
  276. }
  277. }
  278. /**
  279. * 发送邮件<单人发送> return 是否发送成功
  280. *
  281. * @throws MessagingException
  282. * 发送异常
  283. */
  284. public boolean sendMessage() {
  285. try {
  286. Transport.send(mimeMessage);
  287. System.out.println("----------------发送成功----------------");
  288. return true;
  289. } catch (MessagingException e) {
  290. return false;
  291. }
  292. }
  293. /**
  294. * 设置附件
  295. *
  296. * @param file
  297. * 发送文件的路径
  298. * @throws MessagingException
  299. * 发送异常
  300. * @throws IOException
  301. * 文件IO异常
  302. *
  303. */
  304. public boolean setMultipart(String file) throws MessagingException, IOException {
  305. try {
  306. if (multipart == null) {
  307. multipart = new MimeMultipart();
  308. }
  309. multipart.addBodyPart(writeFiles(file));
  310. mimeMessage.setContent(multipart);
  311. //System.out.println("设置邮件附件" + file + "成功!");
  312. return true;
  313. } catch (Exception e) {
  314. return false;
  315. }
  316. }
  317. /**
  318. * 设置附件<添加多附件>
  319. *
  320. * @param fileList<接收List集合>
  321. * @throws MessagingException
  322. * 发送异常
  323. * @throws IOException
  324. * 文件IO异常
  325. */
  326. public boolean setMultiparts(List<String> fileList) throws MessagingException, IOException {
  327. try {
  328. if (multipart == null) {
  329. multipart = new MimeMultipart();
  330. }
  331. for (String s : fileList) {
  332. multipart.addBodyPart(writeFiles(s));
  333. }
  334. mimeMessage.setContent(multipart);
  335. //System.out.println("设置邮件附件" + fileList + "成功!");
  336. return true;
  337. } catch (Exception e) {
  338. return false;
  339. }
  340. }
  341. /**
  342. * 发送文本内容,设置编码方式 <方法与发送附件配套使用> <发送普通的文本内容请使用setText()方法>
  343. *
  344. * @param s
  345. * 发送的文本内容
  346. * @param type
  347. * 编码格式
  348. * @throws MessagingException
  349. */
  350. public boolean setContent(String s, String type) throws MessagingException {
  351. try {
  352. if (multipart == null) {
  353. multipart = new MimeMultipart();
  354. }
  355. bodypart = new MimeBodyPart();
  356. bodypart.setContent(s, type);
  357. multipart.addBodyPart(bodypart);
  358. mimeMessage.setContent(multipart);
  359. mimeMessage.saveChanges();
  360. //System.out.println("设置邮件内容[" + s + "]成功!");
  361. return true;
  362. } catch (Exception e) {
  363. return false;
  364. }
  365. }
  366. /**
  367. * 读取附件
  368. *
  369. * @param filePath
  370. * 文件路径
  371. * @return
  372. * @throws IOException
  373. * @throws MessagingException
  374. */
  375. public BodyPart writeFiles(String filePath) throws IOException, MessagingException {
  376. File file = new File(filePath);
  377. if (!file.exists()) {
  378. throw new IOException("文件不存在!请确定文件路径是否正确");
  379. }
  380. bodypart = new MimeBodyPart();
  381. DataSource dataSource = new FileDataSource(file);
  382. bodypart.setDataHandler(new DataHandler(dataSource));
  383. // 文件名要加入编码,不然出现乱码
  384. bodypart.setFileName(MimeUtility.encodeText(file.getName()));
  385. return bodypart;
  386. }
  387. //带附件集合发生方法
  388. public boolean send(String getMail, String subject, String nick, String content, List<String> fileList) {
  389. try {
  390. setRecipient(getMail); // 输出信息
  391. // 邮件主题
  392. setSubject(subject);
  393. // 发送时间 Date类型(默认即时发送)
  394. setDate(new Date());
  395. // 发送者昵称
  396. setFrom(nick);
  397. // 邮件内容
  398. setContent(content, "text/html; charset=UTF-8");
  399. // 添加附件
  400. setMultiparts(fileList);
  401. } catch (Exception e) {
  402. return false;
  403. }
  404. return sendMessage(); // 是否发送成功;
  405. }
  406. //不带附件集合发生方法
  407. public boolean send(String getMail, String subject, String nick, String content) {
  408. try {
  409. setRecipient(getMail); // 输出信息
  410. // 邮件主题
  411. setSubject(subject);
  412. // 发送时间 Date类型(默认即时发送)
  413. setDate(new Date());
  414. // 发送者昵称
  415. setFrom(nick);
  416. // 邮件内容
  417. setContent(content, "text/html; charset=UTF-8");
  418. } catch (Exception e) {
  419. return false;
  420. }
  421. return sendMessage(); // 是否发送成功;
  422. }
  423. // ----------------------------------------------------------------------------------------------------------------------------
  424. public static void main(String[] args) throws MessagingException, IOException {
  425. SendMail mail = new SendMail();
  426. mail.send("868626@qq.com", "aaaa", "bbb","hello!");
  427. }
  428. }

 

加载全部内容

相关教程
猜你喜欢
用户评论