需要的jar包
mail.jar和activation-1.1.0.jar链接:
https://github.com/chenhaoxiang/Java/tree/master/JavaMail
**
下面演示用新浪邮箱向126邮箱发送邮件:
**
public class Demo {
**发送: 纯文本内容的邮件**
@Test
public void send1() throws Exception{
//跟smtp服务器建立一个连接
Properties p = new Properties();
//设置邮箱-为新浪
p.setProperty("mail.host", "smtp.sina.com");
//认证登录
p.setProperty("mail.smtp.auth", "true");
//建立一个session
Session session = Session.getDefaultInstance(p, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new
//设置用户名和密码 PasswordAuthentication("hnc*******","hncu*****");
}
});
session.setDebug(true);//以debug方式(应答方式)进行通讯
//准备邮件
MimeMessage msg = new MimeMessage(session); //从session中创建邮件
msg.setFrom( new InternetAddress("hncujava@sina.com") );
msg.setRecipient(RecipientType.TO, new InternetAddress("hncujava@126.com"));
msg.setSubject("邮件的主题OKOK!");
msg.setContent("这是第一次用Java发邮件,请多多关照....", "text/plain;charset=utf-8"); //纯文本格式的内容
//msg.setContent("这是第一次用<a href='http://www.baidu.com?age=20'>Java发邮件</a>,请多多关照....", "text/html;charset=utf-8"); //html格式的内容
//发送邮件
Transport.send(msg);
}
@Test //发送:文本内容+附件
public void send2() throws Exception{
Properties p = new Properties();
p.setProperty("mail.host", "smtp.sina.com");
p.setProperty("mail.smtp.auth", "true");//认证登录
Session session = Session.getDefaultInstance(p, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("hncu******","hncu********");
}
});
session.setDebug(true);//以debug方式(应答方式)进行通讯
//准备邮件
MimeMessage msg = new MimeMessage(session); //从session中创建邮件
msg.setFrom( new InternetAddress("hncujava@sina.com") );
msg.setRecipient(RecipientType.TO, new InternetAddress("hncujava@126.com"));
msg.setSubject("邮件的主题OKOK!");
//body1:邮件正文文本内容
MimeBodyPart body1 = new MimeBodyPart();
body1.setContent("这是第一次用<a href='http://www.baidu.com?age=20'>Java发邮件</a>,请多多关照....", "text/html;charset=utf-8"); //html格式的内容
//body2:附件1
MimeBodyPart body2 = new MimeBodyPart();
body2.setDataHandler( new DataHandler( new FileDataSource("./img/a.jpg")));
body2.setFileName( MimeUtility.encodeText("美女1.jpg")); //能够支持中文的附件文件名设置
//body3:附件2
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler( new DataHandler( new FileDataSource("./img/b.jpg")));
body3.setFileName( MimeUtility.encodeText("美女2.jpg")); //不采用编码方式则文件名会中文乱码
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body1);
multipart.addBodyPart(body2);
multipart.addBodyPart(body3);
msg.setContent(multipart);
//发送邮件
Transport.send(msg);
}
}