【已实测通过】JavaMail常用的几种邮件发送方式
来源:互联网 发布:mendeley for mac 编辑:程序博客网 时间:2024/05/16 12:42
【我的Segmfault原文】https://segmentfault.com/a/1190000008114373
前言
关于JavaMail发送邮件的代码,网上随便搜搜就可以找到,但是要么写得简单且没有注释解释,要么写得复杂又非常杂乱。由于项目需要,花了一段时间搜集网上各类案例,熟悉JavaMail邮件发送涉及的配置,取其精华去其糟粕。在功能测试正常可用的前提下,对代码的排版和注释进行梳理调整,提炼出符合自己要求的功能代码,现将它分享给大家,希望大家少走弯路,提高开发效率。代码测试过程出现的问题,请参看《JavaMail邮件发送成功但未收到邮件的问题及解决办法》和《使用geronimo-javamail_1.4发送邮件的有关说明》分析解决。
主要类及功能
1、EmailAuthenticator类:继承Authenticator类的账号密码验证器,主要用于创建邮件会话时调用。
2、EmailSendInfo类:邮件参数信息设置,参数包括账号、密码、SMTP服务器地址和服务端口等。
3、EmailSender类:电子邮件发送器,包含各种邮件发送方法,如文本形式、HTML形式和含附件形式等。
注:请到Oracle官网下载JavaMail的jar包,提供以下参考下载地址:
http://www.oracle.com/technet...
https://java.net/projects/jav...
EmailAuthenticator类
import javax.mail.*; public class EmailAuthenticator extends Authenticator{ private String userName; private String password; public EmailAuthenticator(){} public EmailAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(userName, password); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
EmailSendInfo类
import java.util.Properties;public class EmailSendInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private String[] attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties() { Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; }}
EmailSender类
为了方面大家阅读,我将EmailSender类的内容进行了拆分,测试使用只需要将下面内容组合就可。其中main方法中的部分参数信息需要自行设置,请勿直接粘贴测试。
import配置
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;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;
用于测试的main方法
public static void main(String[] args) { String fromaddr = "XXX@sohu.com"; String toaddr = "XXX@sohu.com";// String title = "【测试标题】Testing Subject-myself-TEXT";// String title = "【测试标题】Testing Subject-myself-HTML";// String title = "【测试标题】Testing Subject-myself-eml文件"; String title = "【测试标题】Testing Subject-myself-eml文件_含多个附件"; String content = "【测试内容】Hello, this is sample for to check send email using JavaMailAPI "; String port = "25"; String host = "smtp.sohu.com"; String userName = "XXX@sohu.com"; String password = "XXX"; EmailSendInfo mailInfo = new EmailSendInfo(); mailInfo.setMailServerHost(host); mailInfo.setMailServerPort(port); mailInfo.setValidate(true); mailInfo.setUserName(userName); mailInfo.setPassword(password); mailInfo.setFromAddress(fromaddr); mailInfo.setToAddress(toaddr); mailInfo.setSubject(title); mailInfo.setContent(content); mailInfo.setAttachFileNames(new String[]{"file/XXX.jpg","file/XXX.txt"}); //发送文体格式邮件// EmailSender.sendTextMail(mailInfo); //发送html格式邮件// EmailSender.sendHtmlMail(mailInfo); //发送含附件的邮件 EmailSender.sendAttachmentMail(mailInfo); //读取eml文件发送// File emailFile = new File("file/EML_myself-eml.eml");// File emailFile = new File("file/EML_reademl-eml文件_含文本附件.eml");// File emailFile = new File("file/EML_reademl-eml文件_含图片附件.eml");// File emailFile = new File("file/EML_reademl-eml文件_含多个附件.eml");// EmailSender.sendMail(mailInfo, emailFile);}
以文本格式发送邮件
public static boolean sendTextMail(EmailSendInfo mailInfo) { boolean sendStatus = false;//发送状态 // 判断是否需要身份认证 EmailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getInstance(pro, authenticator); //【调试时使用】开启Session的debug模式 sendMailSession.setDebug(true); try { // 根据session创建一个邮件消息 MimeMessage mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO,to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject(), "UTF-8"); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent, "UTF-8"); // mailMessage.saveChanges(); //生成邮件文件 createEmailFile("file/EML_myself-TEXT.eml", mailMessage); // 发送邮件 Transport.send(mailMessage); sendStatus = true; } catch (MessagingException ex) { LOG.error("以文本格式发送邮件出现异常", ex); return sendStatus; } return sendStatus; }
以HTML格式发送邮件
public static boolean sendHtmlMail(EmailSendInfo mailInfo){ boolean sendStatus = false;//发送状态 // 判断是否需要身份认证 EmailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); //如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro,authenticator); //【调试时使用】开启Session的debug模式 sendMailSession.setDebug(true); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO,to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件内容 mailMessage.setContent(mailInfo.getContent(), "text/html;charset=utf-8"); //生成邮件文件 createEmailFile("file/EML_myself-HTML.eml", mailMessage); // 发送邮件 Transport.send(mailMessage); sendStatus = true; } catch (MessagingException ex) { LOG.error("以HTML格式发送邮件出现异常", ex); return sendStatus; } return sendStatus; }
读取eml文件后发送邮件
public static boolean sendMail(EmailSendInfo mailInfo, File emailFile) { boolean sendStatus = false;//发送状态 // 判断是否需要身份认证 EmailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getInstance(pro, authenticator); //【调试时使用】开启Session的debug模式 sendMailSession.setDebug(true); try { InputStream source = new FileInputStream(emailFile); // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession, source); // 发送邮件 Transport.send(mailMessage); //【重要】关闭输入流,否则会导致文件无法移动或删除 source.close(); sendStatus = true; } catch (MessagingException e) { LOG.error("以文本格式发送邮件出现异常", e); return sendStatus; } catch (FileNotFoundException e) { LOG.error("FileNotFoundException", e); return sendStatus; } catch (Exception e) { LOG.error("Exception", e); return sendStatus; } return sendStatus; }
以含附件形式发送邮件
public static boolean sendAttachmentMail(EmailSendInfo mailInfo) { boolean sendStatus = false;//发送状态 // 判断是否需要身份认证 EmailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getInstance(pro, authenticator); //【调试时使用】开启Session的debug模式 sendMailSession.setDebug(true); try { // 根据session创建一个邮件消息 MimeMessage mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO,to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject(), "UTF-8"); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart bodyPart = new MimeBodyPart(); //设置TEXT内容// bodyPart.setText(mailInfo.getContent()); // 设置HTML内容 bodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(bodyPart); //设置附件 String[] filenames = mailInfo.getAttachFileNames(); for (int i = 0; i < filenames.length; i++) { // Part two is attachment bodyPart = new MimeBodyPart(); String filename = filenames[i];//1.txt/sohu_mail.jpg// DataSource source = new FileDataSource(filename); FileDataSource source = new FileDataSource(filename); bodyPart.setDataHandler(new DataHandler(source)); bodyPart.setFileName(source.getName()); mainPart.addBodyPart(bodyPart); } // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); //生成邮件文件 createEmailFile("file/EML_reademl-eml文件_含多个附件.eml", mailMessage); // 发送邮件 Transport.send(mailMessage); sendStatus = true; } catch (MessagingException ex) { LOG.error("以文本格式发送邮件出现异常", ex); return sendStatus; } return sendStatus; }
生成邮件文件
public static void createEmailFile(String fileName, Message mailMessage) throws MessagingException { File f = new File(fileName); try { mailMessage.writeTo(new FileOutputStream(f)); } catch (IOException e) { LOG.error("IOException", e); }}
0 0
- 【已实测通过】JavaMail常用的几种邮件发送方式
- JavaMail实现发送邮件实测可用
- 通过javaMail发送邮件
- JavaMail方式发送邮件
- javamail的smtp方式发送邮件实例
- javamail的smtp方式发送邮件实例
- C# 发送邮件的几种方式
- Java发送邮件的几种方式
- javamail通过代理发送邮件
- JavaMail邮件的发送
- JavaMail的发送邮件
- JavaMail邮件的发送
- JavaMail通过发送SSL发送邮件
- Javamail发送邮件后并保存邮件到已发送
- asp.net中发送邮件的几种方式
- android里发送邮件mail的几种方式
- JavaMail发送的方式
- Spring中javaMail通过SMTP发送邮件
- Linux的网络管理
- 制作根文件系统
- C#.Net 垃圾回收机制GC详解
- JZOJ 3824【NOIP2014模拟9.9】渴
- 在Tomcat环境下使用socket通信
- 【已实测通过】JavaMail常用的几种邮件发送方式
- 【NOIP2014八校联考第2场第2试】单词接龙
- js判空的方法
- Rails rspec测试报patch user_path(user) param not found: user的解决
- 生物、医学和计算机领域的学术交流与合作
- C++STL内存配置的设计思想与关键源码分析
- 微信小程序免费HTTPS证书申请搭建教程(1)---申请SSL
- Gym - 101102J J. Divisible Numbers 位运算+优化+前缀和
- 78. Subsets**