准备工作
1. MailConstants类, 定义了一些和邮件发送有关的常量
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [MailConstants.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.utils;
/**
* 发送和接收邮件的常量
*
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public interface MailConstants {
public static final String PROTOCOL_SMTP = "smtp";
public static final String PROTOCAL_POP3 = "pop3";
public static final String PROTOCAL_IMAP = "imap";
public static final String SMTP_HOST_OF_SINA = "smtp.sina.com";
public static final String SMTP_PORT_OF_SINA = "25";
public static final String POP3_HOST_OF_SINA = "pop.sina.com";
public static final String POP3_PORT_OF_SINA = "110";
public static final String IMAP_HOST_OF_SINA = "imap.sina.com";
public static final String IMAP_PORT_OF_SINA = "143";
public static final Boolean IS_SSL_ENABLED_FOR_SINA = false;
public static final Boolean IS_AUTHORIZATION_NEED = true;
public static final Boolean IS_DEBUG_MOD_ENABLED = true;
}
2. MailAuthenticator类, 用来在获得Session时的认证
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [MailAuthenticator.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.utils;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class MailAuthenticator extends Authenticator {
private String username;
private String password;
/**
* 可以只传入username, password由 PasswordUtils 去获取
*
* @param username
* @param password
*/
public MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
3. PasswordUtils用来从数据库查询发件邮箱的密码
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [PasswordUtils.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class PasswordUtils {
public static String readPassword(String username) {
String password = "";
try {
String dbuser = "root";
String dbpass = "123456";
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql:///jdbc";
Class.forName(driverClass);
String sql = "SELECT password FROM Mail_User WHERE username = ?";
Connection connection = DriverManager.getConnection(url, dbuser, dbpass);
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
password = resultSet.getString("password");
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return password;
}
}
下面开始正式的发送邮件示例
发送文本邮件
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [SendingTextMail.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.junit.Before;
import org.junit.Test;
import javamail.utils.MailConstants;
import javamail.utils.PasswordUtils;
/**
* 使用SMTP协议发送纯文本邮件
*
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class SendingTextMail {
// 发件人
private static String emailSender = "javamail_sns@sina.com";
// 收件人
private static String emailRecipient = "18505106250@163.com";
// 初始化连接邮件服务器的会话信息
private static Properties properties = null;
@Before
public void init() {
properties = new Properties();
properties.setProperty("mail.transport.protocol", MailConstants.PROTOCOL_SMTP);
properties.setProperty("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA);
properties.setProperty("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA);
properties.setProperty("mail.smtp.auth", String.valueOf(MailConstants.IS_AUTHORIZATION_NEED));
properties.setProperty("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
}
/**
* 发送简单的文本邮件
*
* @throws Exception
*/
public static void sendTextMail() throws Exception {
// 创建Session实例
Session session = Session.getDefaultInstance(properties);
// 创建MimeMessage实例
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(emailSender));
// 设置邮件主题
message.setSubject("JavaMail - 简单文本文件");
// 设置收件人
message.setRecipient(RecipientType.TO, new InternetAddress(emailRecipient));
// 设置发送时间
message.setSentDate(new Date());
// 设置纯文本内容为邮件正文
message.setText("使用JavaMail发送纯文本文件");
// 保存并生成最终的邮件内容
message.saveChanges();
// 获得Transport实例
Transport transport = session.getTransport();
// 打开连接
transport.connect(emailSender, PasswordUtils.readPassword(emailSender));
// 将message对象传递给transport对象, 将邮件发送出去
transport.sendMessage(message, message.getAllRecipients());
// 关闭连接
transport.close();
}
@Test
public void testSendTextMail() throws Exception {
sendTextMail();
}
}
发送HTML格式的邮件, 定义了两个方法, 分别发送纯HTML邮件和HTML加图片的邮件
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [SendingHtmlMails.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.mail;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
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 org.junit.Before;
import org.junit.Test;
import javamail.utils.MailAuthenticator;
import javamail.utils.MailConstants;
import javamail.utils.PasswordUtils;
/**
* 使用SMTP协议发送Html格式的邮件
*
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class SendingHtmlMails {
private static Properties properties = null;
private static String emailSender = "javamail_sns@sina.com";
private static String emailRecipient = "18505106250@163.com";
@Before
public void init() {
properties = new Properties();
properties.setProperty("mail.transport.protocol", MailConstants.PROTOCOL_SMTP);
properties.setProperty("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA);
properties.setProperty("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA);
properties.setProperty("mail.smtp.auth", String.valueOf(MailConstants.IS_AUTHORIZATION_NEED));
properties.setProperty("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
}
/**
* 发送Html格式的邮件
*
* @throws Exception
*/
public static void sendHtmlMail() throws Exception {
// 创建Session实例
Session session = Session.getInstance(properties,
new MailAuthenticator(emailSender, PasswordUtils.readPassword(emailSender)));
// 创建MimeMessage实例
MimeMessage message = new MimeMessage(session);
// 封装Message的属性
message.setSubject("JavaMail - Html文件");
message.setFrom(new InternetAddress(emailSender));
message.setSentDate(new Date());
message.setRecipient(RecipientType.TO, new InternetAddress(emailRecipient));
message.setContent("<span style='color:red;'>使用JavaMail发送Html邮件</span>", "text/html;charset=UTF-8");
Transport.send(message);
}
/**
* 发送Html附带图片的邮件
*
* @throws Exception
*/
public static void sendHtmlMailWithImage() throws Exception {
// 创建Session实例
Session session = Session.getInstance(properties,
new MailAuthenticator(emailSender, PasswordUtils.readPassword(emailSender)));
// 创建MimeMessage实例
MimeMessage message = new MimeMessage(session);
// 封装Message的属性
message.setSubject("JavaMail - 带有图片的Html邮件", "UTF-8");
message.setFrom(new InternetAddress(emailSender));
message.setSentDate(new Date());
message.setRecipient(RecipientType.TO, new InternetAddress(emailRecipient));
// 抄送
message.setRecipient(RecipientType.CC, new InternetAddress(emailRecipient));
// 密送[不会在邮件收件人名单中显示出来]
message.setRecipient(RecipientType.BCC, new InternetAddress(emailRecipient));
message.setSentDate(new Date());
// 创建一个related类型的MimeMultipart实例, related类型用于组合文本和图片
MimeMultipart mailBodyMP = new MimeMultipart("related");
// 图片部分
MimeBodyPart imagePart = new MimeBodyPart();
// 正文部分
MimeBodyPart htmlPart = new MimeBodyPart();
mailBodyMP.addBodyPart(imagePart);
mailBodyMP.addBodyPart(htmlPart);
// 图片
DataSource dataSource = new FileDataSource(new File("src/javamail/attachments/1.jpg"));
DataHandler dataHandler = new DataHandler(dataSource);
imagePart.setDataHandler(dataHandler);
imagePart.setContentID("image1");
// 邮件正文
MimeMultipart htmlMP = new MimeMultipart("alternative");
MimeBodyPart htmlContent = new MimeBodyPart();
// cid = imageBody.setContentID()中设置的值
htmlContent.setContent("<span style='color:red;'>使用JavaMail发送含有图片的Html邮件<img src=\"cid:image1\"/></span>",
"text/html;charset=utf-8");
htmlMP.addBodyPart(htmlContent);
htmlPart.setContent(htmlMP);
message.setContent(mailBodyMP);
Transport.send(message);
// 将邮件写出到本地, 可以使用FoxMail工具打开查看
// message.writeTo(new FileOutputStream("htmlImageMail.eml"));
}
@Test
public void testSendHtmlMail() throws Exception {
sendHtmlMail();
}
@Test
public void testSendHtmlMailWithImage() throws Exception {
sendHtmlMailWithImage();
}
}
发送HTML+图片+附件的邮件
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [SendingMailWithAttachments.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.mail;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
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;
import org.junit.Before;
import org.junit.Test;
import javamail.utils.MailAuthenticator;
import javamail.utils.MailConstants;
import javamail.utils.PasswordUtils;
/**
* 发送带内嵌图片, 附件的邮件
*
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class SendingMailWithAttachments {
private static Properties properties = null;
private static String emailSender = "javamail_sns@sina.com";
private static String emailRecipient = "18505106250@163.com";
@Before
public void init() {
properties = new Properties();
properties.setProperty("mail.transport.protocol", MailConstants.PROTOCOL_SMTP);
properties.setProperty("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA);
properties.setProperty("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA);
properties.setProperty("mail.smtp.auth", String.valueOf(MailConstants.IS_AUTHORIZATION_NEED));
properties.setProperty("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
}
/**
* 发送Html附带附件的邮件
*
* @throws Exception
*/
public static void sendHtmlMailWithAttachment() throws Exception {
// 创建Session实例
Session session = Session.getInstance(properties,
new MailAuthenticator(emailSender, PasswordUtils.readPassword(emailSender)));
// 创建MimeMessage实例
MimeMessage message = new MimeMessage(session);
// 封装Message的属性
message.setSubject("JavaMail - 带有附件的Html邮件");
message.setSender(new InternetAddress(emailSender, "不落的太阳", "UTF-8"));
// 设置收件人, 抄送, 密送
message.setRecipients(RecipientType.TO,
new Address[] { new InternetAddress(emailRecipient, "不落的太阳", "UTF-8"), });
message.setRecipient(RecipientType.CC, new InternetAddress(emailSender, "不落的太阳", "UTF-8"));
message.setRecipient(RecipientType.BCC, new InternetAddress(emailSender, "不落的太阳", "UTF-8"));
// 设置优先级
message.setHeader("X-Priority", "1");
// 设置回执
message.setHeader("Disposition-Notification-To", emailSender);
// 设置回复人(收件人回复邮件时默认的对方收件人)
message.setReplyTo(InternetAddress.parse("\"" + MimeUtility.encodeText("不落的太阳") + "\"<javamail_sns@sina.com>"));
message.setSentDate(new Date());
// 创建一个mixed类型的MimeMultipart实例, mixed类型用于组合文本, 图片, 附件等
MimeMultipart mailContent = new MimeMultipart("mixed");
// 附件
MimeBodyPart attachment1 = new MimeBodyPart();
DataSource dataSource = new FileDataSource(new File("src/javamail/attachments/1.jpg"));
DataHandler dataHandler = new DataHandler(dataSource);
attachment1.setFileName(MimeUtility.encodeText("附件1.jpg"));
attachment1.setDataHandler(dataHandler);
mailContent.addBodyPart(attachment1);
MimeBodyPart attachment2 = new MimeBodyPart();
dataSource = new FileDataSource(new File("src/javamail/attachments/1.txt"));
dataHandler = new DataHandler(dataSource);
attachment2.setFileName(MimeUtility.encodeText("附件2.txt"));
attachment2.setDataHandler(dataHandler);
mailContent.addBodyPart(attachment2);
// 内容
MimeBodyPart mailBody = new MimeBodyPart();
// 邮件正文内容[html + image]
MimeMultipart mailBodyMP = new MimeMultipart("related");
MimeBodyPart imagePart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
mailBodyMP.addBodyPart(imagePart);
mailBodyMP.addBodyPart(htmlPart);
// 图片
dataSource = new FileDataSource(new File("src/javamail/attachments/1.jpg"));
dataHandler = new DataHandler(dataSource);
imagePart.setDataHandler(dataHandler);
imagePart.setContentID("image1.jpg");
// 邮件内容
MimeMultipart htmlMP = new MimeMultipart("alternative");
MimeBodyPart htmlContent = new MimeBodyPart();
htmlContent.setContent("<span style='color: red'>JavaMail - 带有附件的Html邮件 <img src='cid:image1.jpg' /></span>",
"text/html;charset=UTF-8");
htmlMP.addBodyPart(htmlContent);
htmlPart.setContent(htmlMP);
mailBody.setContent(mailBodyMP);
mailContent.addBodyPart(mailBody);
message.setContent(mailContent);
Transport.send(message);
}
@Test
public void testSendHtmlMailWithAttachment() throws Exception {
sendHtmlMailWithAttachment();
}
}
最后写一个工具类, 可以生成邮件附件, 邮件正文等
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [MailUtils.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
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;
/**
* Email工具类
*
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class MailUtils {
/**
* 根据指定的文件名生成附件
*
* @param fileName
* 文件名
* @return
* @throws Exception
*/
public static MimeBodyPart createMailAttachment(File fileName) throws Exception {
MimeBodyPart attachment = new MimeBodyPart();
DataSource dataSource = new FileDataSource(fileName);
DataHandler dataHandler = new DataHandler(dataSource);
attachment.setDataHandler(dataHandler);
attachment.setFileName(MimeUtility.encodeText(dataSource.getName()));
return attachment;
}
/**
* 根据指定路径的文件名生成附件
*
* @param filePath
* 附件所在的文件路径
* @return
* @throws Exception
*/
public static MimeBodyPart createMailAttachment(String filePath) throws Exception {
File file = new File(filePath);
return createMailAttachment(file);
}
/**
* 根据指定的邮件正文文本和文件[图片或其他]路径生成混合的邮件文本
*
* @param body
* 邮件正文内容
* @param filePath
* 图片或其他文件路径
* @return
* @throws Exception
*/
public static MimeBodyPart createMailBodyContent(String body, String filePath) throws Exception {
// 内容
MimeBodyPart mailBody = new MimeBodyPart();
// 邮件正文内容[html + image]
MimeMultipart mailBodyMP = new MimeMultipart("related");
MimeBodyPart otherPart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
mailBodyMP.addBodyPart(otherPart);
mailBodyMP.addBodyPart(htmlPart);
// 其他内容
DataSource dataSource = new FileDataSource(new File(filePath));
DataHandler dataHandler = new DataHandler(dataSource);
otherPart.setDataHandler(dataHandler);
otherPart.setContentID(MimeUtility.encodeText(dataSource.getName()));
// 邮件内容
MimeMultipart htmlMP = new MimeMultipart("alternative");
MimeBodyPart htmlContent = new MimeBodyPart();
htmlContent.setContent(
"<span style='color: red'>带附件的Html邮件 <img src='cid:" + otherPart.getContentID() + "' /></span>",
"text/html;charset=UTF-8");
htmlMP.addBodyPart(htmlContent);
htmlPart.setContent(htmlMP);
mailBody.setContent(mailBodyMP);
return mailBody;
}
/**
* 根据指定的MimeBodyPart生成邮件
*
* @param bodyParts
* @return
* @throws Exception
*/
public static MimeMultipart createMixedBodyContent(MimeBodyPart... bodyParts) throws Exception {
MimeMultipart mailContent = new MimeMultipart("mixed");
for (MimeBodyPart mimeBodyPart : bodyParts) {
mailContent.addBodyPart(mimeBodyPart);
}
return mailContent;
}
/**
* 根据邮件内容生成eml文件
*
* @param message
* @return
* @throws Exception
*/
public static File createEmlFile(String dir, Message message) throws Exception {
File file = new File(dir + MimeUtility.decodeText(message.getSubject()) + ".eml");
message.writeTo(new FileOutputStream(file));
return file;
}
/**
* 发送已生成的eml文件
*
* @param emlFile
* @param properties
* @param auth
* @throws Exception
*/
public static void sendMailFromEmlFile(File emlFile, Properties properties, Authenticator auth) throws Exception {
Session session = Session.getInstance(properties, auth);
sendMailFromEmlFile(emlFile, session);
}
/**
* 发送已生成的eml文件
*
* @param emlFile
* @param session
* @throws Exception
*/
public static void sendMailFromEmlFile(File emlFile, Session session) throws Exception {
MimeMessage message = new MimeMessage(session, new FileInputStream(emlFile));
Transport.send(message);
}
}
上面邮件工具类的测试
/********************************************************************************
* Project Name [JavaEE_Components]
* File Name [MailUtilsTest.java]
* Creation Date [2015-01-01]
*
* Copyright© ge.y.yang@gmail.com All Rights Reserved
*
* Work hard, play harder, think big and keep fit
********************************************************************************/
package javamail.utils.test;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message.RecipientType;
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 org.junit.Before;
import org.junit.Test;
import javamail.utils.MailAuthenticator;
import javamail.utils.MailConstants;
import javamail.utils.MailUtils;
import javamail.utils.PasswordUtils;
/**
* @author 不落的太阳(Sean Yang aka ShortPeace)
* @version 1.0
* @since jdk 1.8
*
*/
public class MailUtilsTest {
private static Properties properties = null;
private static String emailSender = "javamail_sns@sina.com";
private static String emailRecipient = "18505106250@163.com";
@Before
public void init() {
properties = new Properties();
properties.setProperty("mail.transport.protocol", MailConstants.PROTOCOL_SMTP);
properties.setProperty("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA);
properties.setProperty("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA);
properties.setProperty("mail.smtp.auth", String.valueOf(MailConstants.IS_AUTHORIZATION_NEED));
properties.setProperty("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
}
@Test
public void sendEmailWithEmailUtil() throws Exception {
String fileName = "src/javamail/attachments/1.jpg";
String bodyMessage = "<span style='color:blue'>这是由Email工具发送的邮件</span>";
MimeBodyPart attachment = MailUtils.createMailAttachment(fileName);
MimeBodyPart mailBody = MailUtils.createMailBodyContent(bodyMessage, fileName);
MimeMultipart mailContent = MailUtils.createMixedBodyContent(attachment, mailBody);
Session session = Session.getInstance(properties,
new MailAuthenticator(emailSender, PasswordUtils.readPassword(emailSender)));
MimeMessage message = new MimeMessage(session);
// 封装Message的属性
message.setSubject("工具邮件");
message.setFrom(new InternetAddress(emailSender));
message.setSentDate(new Date());
message.setRecipient(RecipientType.TO, new InternetAddress(emailRecipient));
message.setContent(mailContent);
Transport.send(message);
}
}
相关代码请访问我的git: http://git.oschina.net/shortpeace/JavaEE_Components