1、使用jdk自带的api来实现邮件发送,即JavaMail Api来实现发送,通过里面的Transport.send()发送,其中session用于权限认证,具体实现
用java发邮件,必须要导入新的包
mail.jar – 发邮件的核心包
activation.jar – 对用户和密码加密.
在mail.jar中有三个核心类:
Javax.mail.Session – 是指与邮件服务器会话。整个项目中只要一个就可以了.
Javax.mail.Message(接口) - 准备发送数据信息。
MimeMessage - 可以设置类型的数据信息。
Transport – 它拥有一个方法可以发送Message。
@Test
public void sendMail() throws Exception{
//1,声明properties对象放信息
Properties props = new Properties();
//设置连接哪一台服务器
props.setProperty("mail.host", "smtp.163.com");
//设置是否认证:
props.setProperty("mail.smtp.auth", "true");
//2,声明用户名和密码
Authenticator auth = new Authenticator(){
//返回用户名和密码对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication("xxxxx@163.com", "123456");
return pa;
}
};
//3,获取session对象
Session session = Session.getDefaultInstance(props, auth);
//设置session为调试模式
session.setDebug(true);
//4,声明信息
MimeMessage mm1 = new MimeMessage(session);
//5,设置发件人信息
Address form = new InternetAddress("xxxxx@163.com");
mm1.setFrom(form);
//6,设置收件人 ,RecipientType:发送,抄送,密送 类型
mm1.setRecipient(RecipientType.TO, new InternetAddress("xxx@qq.com"));
//mm1.setRecipient(RecipientType.CC, new InternetAddress(""));//抄送
//7,设置主题
mm1.setSubject("拉面学习通知");
String cont = "请点击 <a href='http://www.fsy158.com/news/31_207'>官网新闻</a>查看祝您发财";
mm1.setContent(cont, "text/html;charset=UTF-8");
//8,发送
Transport.send(mm1);
}
其中的mimeType可是text/plain纯文本。
发送附件:
@Test
public void sendMailWithFile() throws Exception{
Properties ps = new Properties();
ps.setProperty("mail.host", "smtp.163.com");
ps.setProperty("mail.smtp.auth", "true");
Authenticator auth = new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx@163.com","xxx.");
}
};
Session session = Session.getDefaultInstance(ps, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
Address address = new InternetAddress("xxx@163.com");
msg.setFrom(address);
//发送给
msg.setRecipient(RecipientType.TO, new InternetAddress("xxx@qq.com"));
msg.setRecipient(RecipientType.BCC, new InternetAddress("xxx@qq.com"));//密送
msg.setRecipient(RecipientType.CC, new InternetAddress("xxx@qq.com"));//抄送
msg.setSubject("$激情小视频*免费观看");
//声明多部件处理
MimeMultipart mm = new MimeMultipart();
MimeBodyPart body1 = new MimeBodyPart();
//设置附件
DataSource ds1 = new FileDataSource(new File("./img/a.jpg"));
DataHandler dh1 = new DataHandler(ds1);
body1.setDataHandler(dh1);
//必须设置名称
body1.setFileName(MimeUtility.encodeText("美女.jpg"));
MimeBodyPart body2 = new MimeBodyPart();
DataSource ds2 = new FileDataSource(new File("./img/b.jpg"));
DataHandler dh2 = new DataHandler(ds2);
body2.setDataHandler(dh2);
body2.setFileName(MimeUtility.encodeText("美女2.jpg"));
MimeBodyPart body3 = new MimeBodyPart();
DataSource ds3 = new FileDataSource(new File("./img/m.mp3"));
DataHandler dh3 = new DataHandler(ds3);
body3.setDataHandler(dh3);
body3.setFileName(MimeUtility.encodeText("小电影.mp3"));
//添加body到mm
mm.addBodyPart(body1);
mm.addBodyPart(body2);
mm.addBodyPart(body3);
msg.setContent(mm);
//设置发送日期
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -5);
msg.setSentDate(c.getTime());
//发送
Transport.send(msg);
}
可以继续添加MimeBodyPart 来设置正文
MimeBodyPart htmlPart = new MimeBodyPart();String cont = "请点击 <a href='http://www.fsy158.com/news/31_207'>官网新闻</a>查看祝您发财";htmlPart.setContent(cont, "text/html;charset=UTF-8");
mm.addBodyPart(htmlPart);
2、通过spring自带的JavaMailSender来实现,JavaMailSender其实就是对JavaMail进行封装而来的,通过javaMailSender.send()发送。具体实现
1. maven依赖在pom.xml中添加如下依赖:
<springframework.version>4.3.6.RELEASE
org.springframework
spring-core
${springframework.version}
org.springframework
spring-context
${springframework.version}
org.springframework
spring-context-support
${springframework.version}
org.springframework
spring-beans
${springframework.version}
javax.mail
1.4.72.applicationContext.xmlapplicationContext.xml<?xml version="1.0" encoding="UTF-8"?>
3.测试代码import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class JavaMailSenderTest {
@Autowired
private JavaMailSender javaMailSender;
@Test
public void testSimpleTextMail(){ //发送普通文本邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("FX_SKY");// 发送者,可选的
mailMessage.setTo("ricky_feng@163.com");//接受者
mailMessage.setSubject("测试邮件");//主题
mailMessage.setText("Test Email send by javaMailSender!");//邮件内容
javaMailSender.send(mailMessage);
}
@Test
public void testMimeMail() throws Exception { //发送HTML格式的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:嵌入静态资源");
helper.setText("", true);
javaMailSender.send(mimeMessage);
}
@Test
public void testMimeInlineMail() throws Exception { //发送HTML格式含图片的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:嵌入静态资源");
helper.setText("", true);
FileSystemResource logoFile = new FileSystemResource(new File("logo.jpg"));
helper.addInline("logo", logoFile);
javaMailSender.send(mimeMessage);
}
@Test
public void testAttachmentMail() throws Exception { //发送含附件的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);// 第二个参数设置为true,表示允许添加附件
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("发送含图片附件的邮件");
helper.setText("含有附件的邮件");
helper.addAttachment(MimeUtility.encodeText("附件-1.jpg"), new File("E:/attachment1.jpg"));
helper.addAttachment(MimeUtility.encodeText("附件-2.jpg"), new File("E:/attachment2.jpg"));
javaMailSender.send(mimeMessage);
}
}
模板邮件通常我们使用邮件发送服务的时候,都会有一些固定的场景,比如重置密码、注册确认等,给每个用户发送的内容可能只有小部分是变化的。所以,很多时候我们会使用模板引擎来为各类邮件设置成模板,这样我们只需要在发送时去替换变化部分的参数即可。
Java中常用的模板引擎有FreeMarker 和Velocity,下面我们以Velocity为例做演示。
pom.xml 引入velocity 依赖:
org.apache.velocity
velocity
1.7
org.apache.velocity
velocity-tools
2.0
在resources/templates/ 目录下,创建一个模板页面mail.vm:
最后,我们在单元测试中加入发送模板邮件的测试用例,代码如下: @Test
public void testSendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:模板邮件");
VelocityContext context = new VelocityContext();
context.put("username", "Velocity");
context.put("activation_url", "http://www.baidu.com");
Template template = ve.getTemplate("templates/mail.vm");
StringWriter sw = new StringWriter();
template.merge(context, sw);
String text = sw.toString();
helper.setText(text, true);
mailSender.send(mimeMessage);