Java发送邮件遇到的常见需求汇总

基于SMTP发送一个简单的邮件

首先,需要一个认证器:

package No001_基于SMTP的文本邮件;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SimpleAuthenticator extends Authenticator {
private String username;
private String password;
public SimpleAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
} 

然后,书写简单的发送邮件程序:

package No001_基于SMTP的文本邮件;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SMTPSimpleMail {
public static void main(String[] args) throws AddressException, MessagingException {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件查询
String EMAIL_USERNAME = "example_email@163.com";
String EMAIL_PASSWORD = "mypassword";
String TO_EMAIL_ADDRESS = "example_email_too@qq.com";
/* 服务器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 创建Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 邮件信息 */
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(EMAIL_USERNAME));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS));
message.setSubject("how to use java mail to send email.(Title)(001)");
message.setText("how to use java mail to send email.(Content)");
// 发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
} 

各种收件人、抄送人、秘密抄送人,怎么办

认证器沿用,略。

其实就是设置、追加多个收件人、抄送人、秘密抄送人:

package No002_各种发件人收件人抄送人怎么办;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailWithMultiPeople {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件查询
String EMAIL_USERNAME = "example@163.com";
String EMAIL_PASSWORD = "mypassword";
String TO_EMAIL_ADDRESS_1 = "example@163.com";
String CC_EMAIL_ADDRESS_1 = "example@163.com";
String BCC_EMAIL_ADDRESS_1 = "example@163.com";
/* 服务器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 创建Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 发件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress("example@163.com", "Nick Huang");
/* 邮件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC_EMAIL_ADDRESS_1));
message.setSubject("我是一封学习Java Mail的邮件");
message.setText("我是一封学习Java Mail的邮件的内容,请邮件过滤器高抬贵手。");
// 发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
} 

发送附件怎么办

认证器沿用,略。

发送附件demo:

package No003_发送附件怎么办;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMailWithAttachment {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件查询
String EMAIL_USERNAME = "example@163.com";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "example@163.com";
/* 服务器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 创建Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 发件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress(EMAIL_USERNAME);
/* 邮件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("我是一封学习Java Mail的邮件");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("这是一封学习Java Mail的邮件的内容,请邮件过滤器高抬贵手。");
/* 附件 */
BodyPart attachmentPart1 = new MimeBodyPart();
DataSource source = new FileDataSource(new File("D:/文件壹.txt"));
attachmentPart1.setDataHandler(new DataHandler(source));
attachmentPart1.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("文件壹.txt".getBytes()) + "?=");
BodyPart attachmentPart2 = new MimeBodyPart();
source = new FileDataSource(new File("D:/文件贰.txt"));
attachmentPart2.setDataHandler(new DataHandler(source));
attachmentPart2.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("文件贰.txt".getBytes()) + "?=");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(attachmentPart1);
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
// 发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
} 

还有,发送HTML邮件

认证器沿用,略。

其实就是告诉收件客户端用HTML解析渲染:

package No004_发送HTML邮件;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class HowToSendHTMLMail {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件查询
String EMAIL_USERNAME = "example@163.com";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "example@163.com";
/* 服务器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 创建Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 发件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress(EMAIL_USERNAME);
/* 邮件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("如何发送HTML的邮件");
/* 正文 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("<h1>loving you...</h2>", "text/html;charset=gb2312");
/* 封装邮件各部分信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
// 发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
} 

要不,来个工具类?

认证器是一定的,沿用,略。

由于需要设置的属性多且繁杂,用个自己人简单易用的属性命名,所以来一个配置类

package No005_来一个工具类;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MailSenderConfig {
private String SMTPMailHost; // 支持SMTP协议的邮件服务器地址
/* 用于登录邮件服务器 */
private String username;
private String password;
private String subject; // 标题
private String content; // 内容
private String fromMail; // 显示从此邮箱发出邮件
private List<String> toMails; // 收件人
private List<String> ccMails; // 抄送人
private List<String> bccMails; // 秘密抄送人
private List<File> attachments; // 附件
public MailSenderConfig(String sMTPMailHost, String subject,
String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
public String getSMTPMailHost() {
return SMTPMailHost;
}
public void setSMTPMailHost(String sMTPMailHost) {
SMTPMailHost = sMTPMailHost;
}
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;
}
public String getFromMail() {
return fromMail;
}
public void setFromMail(String fromMail) {
this.fromMail = fromMail;
}
public List<String> getToMails() {
return toMails;
}
public void setToMails(List<String> toMails) {
this.toMails = toMails;
}
public List<String> getCcMails() {
return ccMails;
}
public void setCcMails(List<String> ccMails) {
this.ccMails = ccMails;
}
public List<String> getBccMails() {
return bccMails;
}
public void setBccMails(List<String> bccMails) {
this.bccMails = bccMails;
}
public List<File> getAttachments() {
return attachments;
}
public void setAttachments(List<File> attachments) {
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void addToMail (String mail) {
if (this.toMails == null) {
this.toMails = new ArrayList<String>();
}
this.toMails.add(mail);
}
public void addCcMail (String mail) {
if (this.ccMails == null) {
this.ccMails = new ArrayList<String>();
}
this.ccMails.add(mail);
}
public void addBccMail (String mail) {
if (this.bccMails == null) {
this.bccMails = new ArrayList<String>();
}
this.bccMails.add(mail);
}
public void addAttachment (File f) {
if (this.attachments == null) {
this.attachments = new ArrayList<File>();
}
this.attachments.add(f);
}
} 

最后,就是工具类的部分,主要负责几个事情:按照Java Mail规则作些初始化动作、将自定义的属性配置类翻译并以Java Mail规则设置、发送邮件。

还有,需要提下的是,因为工具类所提供的代替设置的属性有限,更多的情况可能不满足需要,所以暴露出MimeMessage,在不满足需求的情况开发者可自行加工配置,而其他部分仍可沿用工具类。

package No005_来一个工具类;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
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;
import No002_各种发件人收件人抄送人怎么办.SimpleAuthenticator;
public class MailSender {
private MailSenderConfig c;
private MimeMessage message;
public MailSender(MailSenderConfig config) throws Exception {
super();
this.c = config;
this.setConfig();
}
/**
* 初始化
* @return
*/
private Session initSession() {
Properties props = new Properties();
if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {
props.put("mail.smtp.host", c.getSMTPMailHost());
}
if (c.getUsername() != null && c.getUsername().length() > 0 &&
c.getPassword() != null && c.getPassword().length() > 0) {
props.put("mail.smtp.auth", "true");
return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));
} else {
props.put("mail.smtp.auth", "false");
return Session.getDefaultInstance(props);
}
}
/**
* 设置Java Mail属性
* @throws Exception
*/
private void setConfig() throws Exception {
this.configValid();
Session s = this.initSession();
message = new MimeMessage(s);
/* 发件人 */
Address[] fromMailArray = new Address[1];
fromMailArray[0] = new InternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
}
}
if (c.getCcMails() != null && c.getCcMails().size() > 0) {
for (String mail : c.getCcMails()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));
}
}
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));
}
}
// 邮件标题
message.setSubject(c.getSubject());
/* 正文 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(c.getContent(), "text/html;charset=gb2312");
/* 封装邮件各部分信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
BodyPart attachmentPart = null;
DataSource ds = null;
if (c.getAttachments() != null && c.getAttachments().size() > 0) {
for (File f : c.getAttachments()) {
attachmentPart = new MimeBodyPart();
ds = new FileDataSource(f);
attachmentPart.setDataHandler(new DataHandler(ds));
attachmentPart.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode(f.getName().getBytes()) + "?=");
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
* 配置校验
* @throws Exception
*/
private void configValid() throws Exception {
if (c == null) {
throw new Exception("配置对象为空");
}
if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {
throw new Exception("SMTP服务器为空");
}
if (c.getFromMail() == null && c.getFromMail().length() == 0) {
throw new Exception("发件人邮件为空");
}
if (c.getToMails() == null || c.getToMails().size() < 1) {
throw new Exception("收件人邮件为空");
}
if (c.getSubject() == null || c.getSubject().length() == 0) {
throw new Exception("邮件标题为空");
}
if (c.getContent() == null || c.getContent().length() == 0) {
throw new Exception("邮件内容为空");
}
}
/**
* 发送邮件
* @throws MessagingException
*/
public void send() throws MessagingException {
Transport.send(message);
}
/**
* 设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性
* @return
*/
public MimeMessage getMessage() {
return message;
}
/**
* 设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性
* @return
*/
public void setMessage(MimeMessage message) {
this.message = message;
}
}
提供一个简单的测试类
package No005_来一个工具类;
import java.io.File;
import javax.mail.internet.MimeMessage;
public class TestCall {
public static void main(String[] args) throws Exception {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件查询
String EMAIL_USERNAME = "example@163.com";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "example@163.com";
String TO_EMAIL_ADDRESS_2 = "example@163.com";
/* 使用情况一,正常使用 */
/*
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST,
"this is test mail for test java mail framework 3.", "this is content 3.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new File("d:/1.txt"));
MailSender ms = new MailSender(c);
ms.send();
System.out.println("sent...");
*/
/* 使用情况二,在更多情况下,工具类所作的设置并不满足需求,故将MimeMessage暴露并 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST,
"this is test mail for test java mail framework 4.", "this is content 4.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new File("d:/1.txt"));
MailSender ms = new MailSender(c);
MimeMessage message = ms.getMessage();
message.setContent("this is the replaced content by MimeMessage 4.", "text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
} 

升级下工具类

在实际使用中,发现在批量发送邮件情况下,工具类的支持不好,比如发送100封邮件,按照上述工具类的逻辑,每发送一封邮件就建立一个连接,那么,100封不就100次了吗?这样严重浪费啊。

于是,针对此点作些升级:

认证器是一定的,沿用,略。

配置类

import java.util.ArrayList;
import java.util.List;
public class MailSenderConfig {
private String SMTPMailHost; // 支持SMTP协议的邮件服务器地址
/* 用于登录邮件服务器 */
private String username;
private String password;
private String subject; // 标题
private String content; // 内容
private String fromMail; // 显示从此邮箱发出邮件
private List<String> toMails; // 收件人
private List<String> ccMails; // 抄送人
private List<String> bccMails; // 秘密抄送人
private List<Attachment> attachments; // 附件
private String contentType = "text/html;charset=utf-8";
/**
* 构造器
* @param sMTPMailHost SMTP服务器
* @param subject 标题
* @param content 内容(默认以“text/html;charset=utf-8”形式发送)
* @param fromMail 发送人地址
*/
public MailSenderConfig(String sMTPMailHost, String subject,
String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
/**
* 构造器
* @param sMTPMailHost SMTP服务器
* @param username 邮件服务器用户名
* @param password 邮件服务器密码
* @param subject 标题
* @param content 内容(默认以“text/html;charset=utf-8”形式发送)
* @param fromMail 发送人地址
*/
public MailSenderConfig(String sMTPMailHost, String username,
String password, String subject, String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.username = username;
this.password = password;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
public void addToMail (String mail) {
if (this.toMails == null) {
this.toMails = new ArrayList<String>();
}
this.toMails.add(mail);
}
public void addCcMail (String mail) {
if (this.ccMails == null) {
this.ccMails = new ArrayList<String>();
}
this.ccMails.add(mail);
}
public void addBccMail (String mail) {
if (this.bccMails == null) {
this.bccMails = new ArrayList<String>();
}
this.bccMails.add(mail);
}
public void addAttachment (Attachment a) {
if (this.attachments == null) {
this.attachments = new ArrayList<Attachment>();
}
this.attachments.add(a);
}
/*
* Getter and Setter
*/
public String getSMTPMailHost() {
return SMTPMailHost;
}
public void setSMTPMailHost(String sMTPMailHost) {
SMTPMailHost = sMTPMailHost;
}
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;
}
public String getFromMail() {
return fromMail;
}
public void setFromMail(String fromMail) {
this.fromMail = fromMail;
}
public List<String> getToMails() {
return toMails;
}
public void setToMails(List<String> toMails) {
this.toMails = toMails;
}
public List<String> getCcMails() {
return ccMails;
}
public void setCcMails(List<String> ccMails) {
this.ccMails = ccMails;
}
public List<String> getBccMails() {
return bccMails;
}
public void setBccMails(List<String> bccMails) {
this.bccMails = bccMails;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
附件实体类
import java.io.File;
/**
* 邮件附件实体类
*/
public class Attachment {
private File file;
private String filename;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFilename() {
if (filename == null || filename.trim().length() == 0) {
return file.getName();
}
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Attachment(File file, String filename) {
super();
this.file = file;
this.filename = filename;
}
public Attachment(File file) {
super();
this.file = file;
}
}
抽象发送类
import java.util.Properties;
import javax.mail.Session;
public abstract class AbstractSessionMailSender {
protected Session session;
/**
* 初始化Session
* @return
*/
public static Session initSession(MailSenderConfig c) {
Properties props = new Properties();
if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {
props.put("mail.smtp.host", c.getSMTPMailHost());
}
if (c.getUsername() != null && c.getUsername().length() > 0 &&
c.getPassword() != null && c.getPassword().length() > 0) {
props.put("mail.smtp.auth", "true");
return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));
} else {
props.put("mail.smtp.auth", "false");
return Session.getDefaultInstance(props);
}
}
/**
* 暴露Getter、Setter提供Session的可设置性,以支持批量发送邮件/发送多次邮件时,可缓存Session
* @return
*/
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
} 

发送类

import javax.activation.DataHandler;
import javax.activation.DataSource;
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;
import javax.mail.internet.MimeUtility;
public class MailSender extends AbstractSessionMailSender {
private MailSenderConfig c;
private MimeMessage message;
public MailSender(MailSenderConfig config) throws Exception {
super();
this.c = config;
this.setConfig();
}
public MailSender(MailSenderConfig config, Session session) throws Exception {
super();
this.c = config;
this.setConfig();
super.setSession(session);
}
/**
* 发送邮件
* @throws MessagingException
*/
public void send() throws MessagingException {
Transport.send(message);
}
/**
* 获取MimeMessage,暴露此对象以便于开发者自行设置个性化的属性(此工具类不支持的方法可由开发人员自行设置,设置完毕设置回来)
* @return
*/
public MimeMessage getMessage() {
return message;
}
/**
* 设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性(此工具类不支持的方法可由开发人员自行设置,设置完毕设置回来)
* @return
*/
public void setMessage(MimeMessage message) {
this.message = message;
}
/**
* 设置Java Mail属性
* @throws Exception
*/
private void setConfig() throws Exception {
this.configValid();
if (session == null) {
session = initSession(c);
}
message = new MimeMessage(session);
/* 发件人 */
Address[] fromMailArray = new Address[1];
fromMailArray[0] = new InternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
}
}
if (c.getCcMails() != null && c.getCcMails().size() > 0) {
for (String mail : c.getCcMails()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));
}
}
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));
}
}
// 邮件标题
message.setSubject(c.getSubject());
/* 正文 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(c.getContent(), c.getContentType());
/* 封装邮件各部分信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
/* 附件 */
BodyPart attachmentPart = null;
DataSource ds = null;
if (c.getAttachments() != null && c.getAttachments().size() > 0) {
for (Attachment a : c.getAttachments()) {
attachmentPart = new MimeBodyPart();
ds = new FileDataSource(a.getFile());
attachmentPart.setDataHandler(new DataHandler(ds));
attachmentPart.setFileName(MimeUtility.encodeText(a.getFilename()));
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
* 配置校验
* @throws Exception
*/
private void configValid() throws Exception {
if (c == null) {
throw new Exception("配置对象为空");
}
if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {
throw new Exception("SMTP服务器为空");
}
if (c.getFromMail() == null && c.getFromMail().length() == 0) {
throw new Exception("发件人邮件为空");
}
if (c.getToMails() == null || c.getToMails().size() < 1) {
throw new Exception("收件人邮件为空");
}
if (c.getSubject() == null || c.getSubject().length() == 0) {
throw new Exception("邮件标题为空");
}
if (c.getContent() == null || c.getContent().length() == 0) {
throw new Exception("邮件内容为空");
}
}
}
一个Junit的测试类
import java.io.File;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.junit.Test;
public class ReadMe {
/* 必需的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此邮件服务器地址,自行去所属邮件服务器描述页查询
String EMAIL_USERNAME = "example@163.com";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "example@163.com";
/* 选填的信息 */
String TO_EMAIL_ADDRESS_2 = "example@163.com";
@Test
public void case1() throws Exception {
/* 使用情况一,正常使用 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST,
"this is a mail for test java mail framework in case1.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
MailSender ms = new MailSender(c);
ms.send();
System.out.println("sent...");
}
@Test
public void case2() throws Exception {
/* 使用情况二,在更多情况下,工具类所作的设置并不满足需求,故将MimeMessage暴露以便于开发者自行设置个性化的属性 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST,
"this is a mail for test java mail framework in case2.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
MailSender ms = new MailSender(c);
MimeMessage message = ms.getMessage();
message.setContent("this is the replaced content by MimeMessage in case2.", "text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
@Test
public void case3() throws Exception {
/* 使用情况三,多次发送邮件,可缓存Session,使多次发送邮件均共享此Session,以减少重复创建Session
* 同时需注意缓存的Session的时效性
*/
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST,
"this is the first mail for test java mail framework to share session in case3.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
Session session = MailSender.initSession(c);
MailSender ms = new MailSender(c, session);
ms.send();
c.setSubject("this is the second mail for test java mail framework to share session in case3.");
c.setContent("this is content 2.");
ms = new MailSender(c, session);
ms.send();
System.out.println("sent...");
}
} 

总结

目前,我遇到的需求就是这么多,如日后遇见其他常见的需求并有时间,会进一步添加。

以上所述是小编给大家介绍的Java发送邮件遇到的常见需求汇总的全部叙述,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • 如何使用JavaMail发送邮件

    现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能,用户注册成功之后,就将用户的注册信息以Email的形式发送到用户的注册邮箱当中,实现发送邮件功能就得借助于JavaMail了. 一.搭建开发环境 1.1.创建Web项目 1.2.用户注册的Jsp页面 register.jsp <%@ page language="java" pag

  • Java使用JavaMail发送邮件的方法

    本文实例讲述了Java使用JavaMail发送邮件的方法.分享给大家供大家参考,具体如下: 代码一.Email_Autherticator.java 服务器验证代码 import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class Email_Autherticator extends Authenticator { String username = "你邮箱的用户名"; S

  • java发送邮件示例讲解

    本文实例讲解了java发邮件的详细过程,供大家参考,具体内容如下 1.邮件协议 发邮件的:SMTP (Simple Mail Transport  Protocal) 收邮件的协议:pop3 (Post Office Protocal 3) IMAP 新协议 发邮件也可以收邮件. (一步步的与服务器交互) SMTP : 2.收发邮件的过程: 一般情况下,smtp和pop3是两个服务器(主机). Smtp邮件的端口为25. POP3 端口 为110. 发邮件示例 1).安装foxmail: 2).

  • Java基于JavaMail实现向QQ邮箱发送邮件

    最近项目在做新闻爬虫,想实现这个功能:爬虫某个页面失败后,把这个页面的 url 发到邮箱.最终实现的效果图如下,后期可以加上过滤标签.失败状态码等,方便分类搜索异常. 开发人员可以根据邮件里的 url 和堆栈信息,分析爬虫失败的原因. 是不是服务器 down 了? 还是爬虫的 Dom 解析没有解析到内容? 还是正则表达式对于这个页面不适用? 开启SMTP服务 在 QQ 邮箱里的 设置->账户里开启 SMTP 服务 注意开启完之后,QQ 邮箱会生成一个授权码,在代码里连接邮箱使用这个授权码而不是原

  • Java发送邮件javax.mail的实现方法

    直接上源码: 1. 邮件的基本信息(方便就直接设置为静态了) 下面最好是做为一个javabean package com.lgf.Email; import java.util.Date; public class EmailMessage { /** * 邮件的信息,可以自己进行设置. * 为了方便直接全部设置为静态 */ // 收件人邮箱 public static String TO = "xxx@xxx.com"; // 发件人邮箱 public static String F

  • java发送邮件的具体实现

    首先是继承自javax.mail.Authenticator的一个具体类.getPasswordAuthentication()方法也就是构建一个PasswordAuthentication对象并返回,有点费解JAVA Mail这样的设计意图,可能javax.mail.Authenticator为我们提供了附加的保证安全的验证措施吧. 复制代码 代码如下: package com.mzule.simplemail; import javax.mail.Authenticator;import j

  • Java mail 发送邮件的具体实例

    今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题.为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用.呵呵 以下三段代码是我的全部代码,朋友们如果想用,直接复制即可.jar包因为我不知道怎么传到javaeye上,所以朋友们回去自己打吧. 我的代码有三个类: 第一个类:MailSenderInfo.java 复制代码 代码如下: package com.util.mail;/** * 发送邮件需要使用的基本信息 */ import java.util.P

  • java邮件发送的实现

    邮件是在日常生活中,这篇文章主要介绍了java实现基于SMTP发送邮件的方法,实例分析了java基于SMTP服务发送邮件的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下. 1.写一个 MailSendProper 类封装需要的属性 import java.util.Properties; public class MailSendProper { private String Host ; //发送邮件服务器的ip private String Port ; //发送邮件服务器的端口号 p

  • Java Mail与Apache Mail发送邮件示例

    一.邮件简介 一封邮件由很多信息构成,主要的信息如下,其他的暂时不考虑,例如抄送等: 1.收件人:收件人的邮箱地址,例如xxx@xx.com 2.收件人姓名:大部分的邮件显示时都会显示,例如loadfate 779554589@qq.com 3.发件人:发件人的邮箱地址 4.发件人姓名: 5.主题:邮件的标题 6.内容及附件:邮件的主要内容 二.使用Java发邮件的通用步骤 一般的项目中没有单独的邮件服务器,一般情况下都是使用别人的服务器. 1.设置smtp服务器:不同的邮件服务器有不同的地址,

  • java实现基于SMTP发送邮件的方法

    本文实例讲述了java实现基于SMTP发送邮件的方法.分享给大家供大家参考.具体实现方法如下: import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Tra

  • Java实现发送邮件功能时碰到的坑

    之前用163邮箱发邮件时明明是成功的,但是使用中国移动自己的邮箱时,无论如何在linux服务器中都发送不成功,一开始报如下错误: javax.mail.MessagingException: Unknown SMTP host: mail.chinamobilesz.com at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1959) ~ [mail-1.4.7.jar:1.4.7] at com.sun.mail.

  • java实现163邮箱发送邮件到qq邮箱成功案例

    下载和上传附件.发送短信和发送邮件,都算是程序中很常用的功能,之前记录了文件的上传和下载还有发送短信,由于最近比较忙,邮件发送的功能就没有时间去弄,现在终于成功以163邮箱发送邮件到qq邮箱,以下是相关代码,具体解释可以参考代码中注释: package test; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.ut

  • JavaWeb中JavaMail创建邮件和发送邮件

    一.RFC882文档简单说明 RFC882文档规定了如何编写一封简单的邮件(纯文本邮件),一封简单的邮件包含邮件头和邮件体两个部分,邮件头和邮件体之间使用空行分隔. 邮件头包含的内容有: from字段 --用于指明发件人 to字段     --用于指明收件人 subject字段  --用于说明邮件主题 cc字段    -- 抄送,将邮件发送给收件人的同时抄送给另一个收件人,收件人可以看到邮件抄送给了谁 bcc字段 -- 密送,将邮件发送给收件人的同时将邮件秘密发送给另一个收件人,收件人无法看到邮

  • JavaWeb中使用JavaMail实现发送邮件功能实例详解

    现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能,用户注册成功之后,就将用户的注册信息以Email的形式发送到用户的注册邮箱当中,实现发送邮件功能就得借助于JavaMail了. 一.搭建开发环境 1.1.创建Web项目 1.2.用户注册的Jsp页面 register.jsp <%@ page language="java" pag

  • java使用Socket实现SMTP协议发送邮件

    本文实例为大家分享了java 利用Socket实现SMTP协议发送邮件的具体代码,供大家参考,具体内容如下 package mail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; impo

随机推荐