JavaMail概述:

       JavaMail是由Sun定义的一套收发电子邮件的API,不同的厂商可以提供自己的实现类。但它并没有包含在JDK中,而是作为JavaEE的一部分。

javaMail常见的邮件协议包括:

SMTP:简单的邮件传输协议,用于发送电子邮件协议;

POP3:用于接收电子邮件的标准邮件协议;

IMAP:互联网消息协议,是POP3的代替协议

这三种协议都有对应SSL加密传输的协议,分别是SMTPS,POP3S和IMAPS。

下面我们看一个例子来简单的了解一下Javamail

1.使用Spring发送带附件的电子邮件

大配置

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="192.168.8.71"></property><!-- 服务器 -->
<property name="port" value=""></property><!-- 端口 -->
<property name="username" value="wxk"></property><!-- 用户名 -->
<property name="password" value="wxk"></property><!-- 密码 -->
<property name="protocol" value="smtp" ></property><!-- 协议 -->
<property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 -->
<property name="javaMailProperties">
<props>
<!-- 设置SMTP服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean> <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment">
<property name="mailSender" ref="mailSender"></property>
</bean> </beans>

log4j.properties

log4j.rootLogger=info,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n
//测试
package cn.bdqn; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); try{
MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment");
mailWithAttach.send();
}catch(Exception e){
System.out.print(e.toString());
}
}
}

MailWithAttachment

package cn.bdqn;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility; import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper; public class MailWithAttachment {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
} public void send() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]"); helper.setSubject("等待是种执着");
helper.setText("青鸟的岁月似流年,又有多少青春如风逝去,不要让这座城市只留下无尽的回忆,却没有留下我们一起走过的青春," +
"青春不是生命的一瞬,而是一种自然的心境!");
//添加附件1
ClassPathResource file1 = new ClassPathResource("/cn/bdqn/attachfiles/QQ图片20161214191111.jpg");
helper.addAttachment(file1.getFilename(), file1.getFile());
//添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
ClassPathResource file2 = new ClassPathResource("/cn/bdqn/attachfiles/附件测试文件.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
mailSender.send(mimeMessage);
}
}

javaMail-LMLPHP

上传邮件成功

2.使用Spring发送简单邮件

大配置和log4j还要架包同上省略

Mail
package cn.bdqn;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage; public class Mail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void send(){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo("[email protected]");
message.setSubject("会议通知fsb发布");
message.setText("jerry你好!请于明天下午16:00 准时到B01会议室召开技术讨论会。");
mailSender.send(message);
}
}

MailTest

package cn.bdqn;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
/*测试简单邮件*/
Mail mail = (Mail)context.getBean("mail");
mail.send();
}
}

  

3.使用Spring邮件服务和FreeMarker模板技术发送邮件

javaMail-LMLPHP

大配置和log4j还要架包同上省略

实体层

package cn.bdqn.pojo;

public class Mail {
private String to;
private String subject;
private String content;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
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;
} }

LeaveService

package cn.bdqn.service;

import cn.bdqn.pojo.Mail;

public class LeaveService {
private MailService mailService;
public void setMailService(MailService mailService) {
this.mailService = mailService;
} public void updateLeave(){
//省略审批请假申请
//查询数据库获取相关信息
String approver = "张来";
Mail mail = new Mail();
mail.setTo("[email protected]");
mail.setSubject("请假流程确认邮件");
StringBuffer sb = new StringBuffer();
sb.append("<html><head>");
sb.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
sb.append("<head><body>");
sb.append("<font color='blue' size='4' face='Arial'>");
sb.append("OA系统温馨提示:</font><br/><br/>");
sb.append("    ");
sb.append("在OA系统中,您提交的“请假流程” "+ approver +" 已经审批完成,点击如下链接可登陆系统查看流程,谢谢。" +
"如果登录时忘记密码,可以在网站登录页找回。<br/>");
sb.append("<br/><br/>    <a href='http://www.jboa.com'>http://www.jboa.com</a>");
sb.append("<br/><br/>    -----本邮件为系统自动发出,请勿回复-----");
mail.setContent(sb.toString());
try{
mailService.send(mail);
}catch(Exception e){
e.printStackTrace();
} } }

  MailService

package cn.bdqn.service;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper; import cn.bdqn.pojo.Mail; public class MailService {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
} public void send(Mail mail) throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("[email protected]");
helper.setTo(mail.getTo());
helper.setSubject(mail.getSubject()); helper.setText(mail.getContent(),true);
mailSender.send(mimeMessage);
System.out.print("发送完成!");
}
}

  MailTest

package cn.bdqn;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.bdqn.service.LeaveService; public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
LeaveService service = (LeaveService)context.getBean("leaveService");
service.updateLeave();
}
}

最简单的站内传送Email上传,不需要大配置、log4j、架包

定义一个EmailAuthenticator类 extend Authenticator

public class EmailAuthenticator extends Authenticator {
private String username; private String userpass; public void setUsername(String username) {
this.username = username;
} public void setUserpass(String userpass) {
this.userpass = userpass;
} public EmailAuthenticator() {
} public EmailAuthenticator(String username, String userpass) {
this.username = username;
this.userpass = userpass;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,userpass);
}

定义Mail.java用来定义发件人和收件人的信息

public class Mail {
private String mailServer,from,to,mailSubject,mailContent;
private String username,password;
public Mail(){
//设置邮件信息
//进行认证登录的用户名
username="[email protected]";
//认证密码
password="bxq";
//认证的邮箱对应的邮件服务器
mailServer="192.168.8.71";
//发件人信息
from="bxq";
//收件人信息
to="[email protected]";
//邮件标题
mailSubject="我们都是好孩子";
//邮件内容
mailContent="这是一封测试邮件!如有雷同,纯属不可能";
}
//设置邮件服务器
@SuppressWarnings("static-access")
public void send(){
Properties prop=System.getProperties();
//指定邮件server
prop.put("mail.smtp.host", mailServer); //是否开启认证
prop.put("mail.smtp.auth", "true"); //smtp协议的
prop.put("mail.smtp.port", "25");
//产生Session服务
EmailAuthenticator mailauth=new EmailAuthenticator(username, password);
Session mailSession=Session.getInstance(prop,(Authenticator)mailauth);
try {
//封装Message对象
Message message=new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); //发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人
message.setSubject(mailSubject);
//设置内容(设置字符集处理乱码问题)
message.setContent(mailContent,"text/html;charset=gbk");
message.setSentDate(new Date());
//创建Transport实例,发送邮件
Transport tran=mailSession.getTransport("smtp");
tran.send(message,message.getAllRecipients());
tran.close(); } catch (Exception e) {
e.printStackTrace();
}
}

测试 Test.java

public class Test {
public static void main(String[] args) {
Mail mail=new Mail();
mail.send();
System.out.println("success!");
} }

javaMail-LMLPHP

Transport和Store:传输和存储

邮件操作只有发送或接收两种处理方法,javaMail将两个不同的操作描述传输(javax.mail.Transport)和存储(javax.mail.Store),传输对应邮件的发送,而存储对应邮件的接收。

Session提供了几个用于创建Transport和Store实例的方法,在具体讲解这些方法之前,我们事先了解一下Session创建Transport和Store的内部机制。我们知道提供者在javamail.providers配置文件中为每一种支持的邮件协议定义了实现类,Session根据协议类型(stmp、pop3等)和邮件操作方式(传输和存储)这两个信息就可以定位到一个实例类上。比如,指定stmp协议和transport类型后,Session就会使用com.sun.mail.smtp.SMTPTransport实现类创建一个Transport实例,而指定pop3协议和store类型时,则会使用com.sun.mail.pop3.POP3Store实例类创建一个Store实例。Session提供了多个重载的getTransport()和getStore()方法,这些方法将根据Session中Properties属性设置情况进行工作,影响这两套方法工作的属性包括:

属性名

说明

mail.transport.protocol

默认的邮件传输协议,例如,smtp

mail.store.protocol

默认的存储邮件协议,例如:pop3

mail.host

默认的邮件服务地址,例如:192.168.67.1

mail.user

默认的登陆用户名,例如:zapldy

05-08 15:41