需要Jar包,如果使用jdk1.4需要手动加入jaf包,1.5以后不需要了
下载地址:http://www.oracle.com/technetwork/java/javamail/index-138643.html
概念:
POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件
比如foxmail、outlook都是pop3服务器
IMAP: 和P0P3一致的,客户服务器同步,比如网页
SMTP是发信的。
邮件服务器服务端就是smtp服务器,使用之前必须在邮件服务端设置中把pop3/imap协议打开
原理: 使用第三方的stmp服务器来发送邮件
例子1: 简单文本内容发送:TestMail01
**public class TestMail01 {
public static void main(String[] args) {
Transport tran = null;
try {
Properties props = new Properties();
// 设置邮件发送的协议,一般都是SMTP协议
props.setProperty("mail.transport.protocol", "smtp");
// 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询
// 在设置中可以找到
props.setProperty("mail.host", "smtp.sina.com");
// 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件
props.setProperty("mail.smtp.auth", "true");
// 创建session
Session session = Session.getInstance(props);
//打开邮件发送的调试功能,可以看到邮件的发送过程
session.setDebug(true);
// 创建Message对象,通过这个对象来设置邮件的发送信息
Message msg = new MimeMessage(session);
// 设置邮件的标题
msg.setSubject("大家来看看,我通过java发邮件了!");
// 设置邮件的内容,使用setText是设置纯文本的内容
msg.setText("唔哈哈哈哈哈哈!通过java发垃圾邮件了");
// 设置邮件从什么地方发送的
msg.setFrom(new InternetAddress("denganzhi11@sina.com"));
// 设置邮件的发送人,此时表示的发送人
msg.setRecipients(RecipientType.TO, InternetAddress.parse("denganzhi11@163.com,2998677551@qq.com"));
// 设置邮件的抄送人
//msg.setRecipients(RecipientType.CC, InternetAddress.parse("kh_itat@sohu.com,ynkonghao@gmail.com"));
/**
* 创建Transport来完成邮件的发送
*/
tran = session.getTransport();
/**
* 连接用户名和密码
*/
tran.connect("denganzhi11@sina.com", " ooxx“)
/**
* 发送邮件,此时如果msg中设置了收件人,但是在sendMessage的第二个参数中没有设置的话
* 也不会发送,所以使用tran.sendMessage来发送邮件不是一种推荐的方式
* 应该使用Transport.send(msg);来发送邮件
*/
tran.sendMessage(msg, new InternetAddress[]{new InternetAddress("denganzhi11@163.com")});
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
if(tran!=null) tran.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}**
例子2: 发送HTML文本: TestMail02
public class TestMail02 {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
/**
* 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询
*/
props.setProperty(“mail.host”, “smtp.sina.com”);
/**
* 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件
*/
props.setProperty(“mail.smtp.auth”, “true”);
/**
* 当需要使用Transport.send发送时,需要将用户名和密码设置到Session中
*/
Session session = Session.getDefaultInstance(props,new Authenticator() {
/**
* 通过Authenticator中 的getPasswordAuthentication的方法来设置邮箱的用户名和密码
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“denganzhi11@sina.com”, “ooxx”);
}
});
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("denganzhi11@sina.com"));
msg.setRecipient(RecipientType.TO,new InternetAddress("denganzhi11@163.com"));
msg.setSubject("一封邮件");
/**
* 通过以下方式可以创建一个html的文档
*/
msg.setContent("<h1 style='color:red'>这是一封邮件</h1>","text/html;charset=utf-8");
/**
* 使用Transport的static方法send发送邮件需要在Session创建时来确定访问的密码
*/
Transport.send(msg);
System.out.println("------------------------------------------");
// getDefaultInstance 和 getInstance 区别
// 这里是第二种发送方式:
/* Properties props1 = new Properties();
props1.setProperty("mail.transport.protocol", "smtp");
*//**
* 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询,错误的
*//*
props1.setProperty("mail.host", "smtp1.sohu.com");
*//**
* 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件
*//*
props1.setProperty("mail.smtp.auth", "true");
*//**
* 当使用getDefaultInstance的时候,会查找Session是否在内存中已经存在,如果存在就不会再去
* 读取新的Properties中的配置,而是直接使用内存中已经存在的配置信息,所以此时可以不设置props
* 都可以访问.
* 所以如果在一个项目中可能会涉及到使用多个邮箱发送邮件,就不要使用getDefaultInstance来处理
* 在一些特殊的情况:如果邮箱验证此时只会通过一个邮箱发出邮件,就可以使用getDefaultInstance来处理
*//*
Session s2 = Session.getInstance(props1, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 这里设置用户名和密码
return new PasswordAuthentication("kh_itat","kh1234");
}
});
Message msg2 = new MimeMessage(s2);
msg2.setFrom(new InternetAddress("kh_itat@sohu.com"));
msg2.setRecipient(RecipientType.TO,new InternetAddress("kh_itat@sina.com"));
msg2.setSubject("一封发给自己的邮件");
*//**
* 通过以下方式可以创建一个html的文档
*//*
msg2.setContent("<h1 style='color:red'>这是一封发给自己的邮件</h1>","text/html;charset=utf-8");
*//**
* 使用Transport的static方法send发送邮件需要在Session创建时来确定访问的密码
*//*
Transport.send(msg2);*/
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
区别: getDefaultInstance和getInstance区别:
在一个项目中可能会涉及到使用多个邮箱发送邮件,使用getInstance 否则使用getDefaultInstance
例子3:
如果一个邮件中有多个附件、并且内容中含有图片和文字的时候
组成:
如果body是plain text类型或者html类型,那么直接使用setContext来创建内容
如果有附件,需要使用Mutipart来创建,Mutipart不能最直接添加内容,
需要首先创建BodyPart中设置内容之后,让BodyPart添加到mutipart才行
看图:
代码:
**public class TestMail03 {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
/**
* 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询
*/
props.setProperty(“mail.host”, “smtp.sina.com”);
/**
* 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件
*/
props.setProperty(“mail.smtp.auth”, “true”);
/**
* 当需要使用Transport.send发送时,需要将用户名和密码设置到Session中
*/
Session session = Session.getDefaultInstance(props,new Authenticator() {
/**
* 通过Authenticator中 的getPasswordAuthentication的方法来设置邮箱的用户名和密码
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“denganzhi11@sina.com”, “ooxx”);
}
});
session.setDebug(true);
Message msg = new MimeMessage(session);
/**
* 使用MimeUtility.encodeText可以将中文编码
*/
msg.setFrom(new InternetAddress(MimeUtility.encodeText("java培训")+"<denganzhi11@sina.com>"));
msg.setRecipient(RecipientType.TO,new InternetAddress(MimeUtility.encodeText("培训学员")+"<denganzhi11@163.com>"));
msg.setSubject("一封邮件");
/**
* 创建整个邮件的Multipart,因为邮件的内容已经不仅仅只是纯文本或者纯html文本,而需要添加
* 相应的附件,此时就得通过Multipart来创建
*/
Multipart emailPart = new MimeMultipart();
/**
* Multipart不能直接加入内容,需要通过BodyPart来加入内容,假设有两个附件就需要三个BodyPart
* 两个用来存储附件,一个用来存储邮件的正文
*/
/*****************两个附件***************************/
MimeBodyPart att1 = new MimeBodyPart();
/**
* 为第一个附件设置文件,DataHandler是在JAF包中,如果使用的是jdk1.4的版本需要手动下载这个包
*/
att1.setDataHandler(new DataHandler(new FileDataSource("d:/user.log")));
att1.setFileName("user.log");
/**
* 创建了第二个附件
*/
MimeBodyPart att2 = new MimeBodyPart();
att2.setDataHandler(new DataHandler(new FileDataSource("d:/order.jsp")));
//要解决中文的问题需要通过一个MimeUtility这个类来编码中文
att2.setFileName(MimeUtility.encodeText("测试.jsp"));
/********************************************/
MimeBodyPart content = new MimeBodyPart();
/**
* 由于文件的正文还有图片和内容,所以也需要通过Multipart来创建
*/
MimeMultipart contentMultipart = new MimeMultipart();
/**
* 然后再创建相应的BodyPart来设置内容
*/
MimeBodyPart imgBody = new MimeBodyPart();
/**
* 创建了正文中的图片内容
*/
imgBody.setDataHandler(new DataHandler(new FileDataSource("d:/02.jpg")));
/**
* 为这个图片设置一个id,在正文中可以通过cid:xxx来访问
*/
imgBody.setContentID("smile");
MimeBodyPart htmlBody = new MimeBodyPart();
htmlBody.setContent("<h1>这个是一个带有附件的图片</h1><img src='cid:smile'/>", "text/html;charset=utf-8");
contentMultipart.addBodyPart(imgBody);
contentMultipart.addBodyPart(htmlBody);
//完成了邮件正文的设置
content.setContent(contentMultipart);
/**
* 设置邮件的信息
*/
//添加第一个附件
emailPart.addBodyPart(att1);
//添加第二个附件
emailPart.addBodyPart(att2);
//添加邮件正文
emailPart.addBodyPart(content);
//设置邮件的信息
msg.setContent(emailPart);
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}**
缺点: 复杂拼接
例子4: spring3整合javamail
spring整合javamail,看spring文档,有详细说明,spring文档中非常详细
功能特点:spring对邮件内容封装的非常好,不用拼接了
例子:
1.beans.xml:
true
2. @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“/beans.xml”)
public class TestMail {
@Resource(name="mailSender")
public JavaMailSender mailSender;
@Test
public void test01() {
try {
//创建mimeMessage
MimeMessage msg = mailSender.createMimeMessage();
//通过MimeMessageHelper来完成对邮件信息的创建
MimeMessageHelper helper = new MimeMessageHelper(msg,true, "utf-8");
// 发件人
helper.setFrom("denganzhi11@sina.com");
// 发给
helper.setTo("denganzhi11@163.com");
helper.setSubject("通过Spring发的哦!");
//设置邮件的正文
// 这里一般是富文本编辑器
helper.setText("<div style='color:red;font-size:15px;'>通过Spring来发送邮件</div>" +
"<img src='cid:sss'/>kajsdkjsadf<img src='cid:ddd'/>ksjdhfksjdhf<img src='cid:aaa'/>", true);
//添加附件
helper.addAttachment(MimeUtility.encodeText("日志"), new FileSystemResource("d:/a.log"));
//添加邮件内容中信息
FileSystemResource fsr = new FileSystemResource("d:/a.log");
helper.addInline("sss", fsr);
helper.addInline("ddd", new URLDataSource(new URL("http://img3.douban.com/lpic/s24494223.jpg")));
helper.addInline("aaa", new URLDataSource(new URL("http://img3.douban.com/lpic/s11159090.jpg")));
// 邮件发送
mailSender.send(msg);
} catch (MailException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/* public static void main(String[] args) {
TestMail t1=new TestMail();
t1.test01();
}
*/
}
注意:在发送邮件的时候最好把邮件发送放在线程中,
spring 提供了默认线程池,封装非常好, org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
- 应用练习:
富文本编辑把富文本编辑内容转换为邮件
例子:MessageService下的add