标签:
【工程截图】
【代码实例】
package com.Higgin.mail.demo;
import java.io.File;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.junit.Test;
public class JavaMailDemo02 {
@Test
public void testDemo01() throws AddressException, MessagingException{
/*** 1.得到Session ***/
Properties props=new Properties();
props.setProperty("mail.host", "smtp.163.com");//设置邮件服务器地址
props.setProperty("mail.smtp.auth", "true"); //设置邮件服务器是否需要登录认证
Authenticator auth=new Authenticator(){ //创建认证器
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("邮箱用户名","邮箱密码"); //用户名和密码
}
};
Session session=Session.getInstance(props,auth); //获取Session对象
/*** 2.创建MimeMessage ***/
MimeMessage msg=new MimeMessage(session); //创建邮件对象
msg.setFrom(new InternetAddress("511861467@qq.com")); //设置发件人
msg.addRecipient(RecipientType.TO, new InternetAddress("张三@126.com")); //设置收件人
msg.addRecipient(RecipientType.CC, new InternetAddress("李四@qq.com")); //设置收件人(抄送)
msg.addRecipient(RecipientType.BCC, new InternetAddress("王五@163.com"));//设置收件人(暗送)
msg.setSubject("这是一份测试邮件2"); //设置发送的邮件的标题
//指定邮件内容,以及内容的MIME类型
MimeMultipart partList=new MimeMultipart();
msg.setContent(partList); //把邮件的内容设置为多部分的集合对象
//创建一个部件1
MimeBodyPart part1=new MimeBodyPart();
//给部件指定内容
part1.setContent("又是一封测试邮件","text/html;charset=utf-8");
//把部件添加到集合中
partList.addBodyPart(part1);
//创建一个部件2
MimeBodyPart part2=new MimeBodyPart();
//给部件指定附件
part2.attachFile(new File("c:/华仔.jpg"));
//指定附件的名称
part2.setFileName(MimeUtility.encodeText("刘德华.jpg")); //解决中文乱码
//把部件添加到集合中
partList.addBodyPart(part2);
/*** 3.发送邮件 ***/
Transport.send(msg);
}
}
标签:
原文地址:http://www.cnblogs.com/HigginCui/p/5764280.html