Java Mail API

1. 使用容器的MAILSESSION(已定义好服务器属性)


MimeMessage mimeMsg = new MimeMessage(session);//创建MIME邮件对象

.......

Transport.send(mimeMsg); //发送邮件

2.使用属性文件MailServer.properties 定义邮件服务器属性

SmtpHost=smtp.163.com
User=lisa_19982000
Password=king
Sender=lisa_19982000@163.com
Subject=Hello

使用类中:

   InputStream is = getClass().getResourceAsStream("MailServer.properties");
Properties prop = new Properties();
prop.load(is);
this.setSmtpHost(prop.get("SmtpHost").toString());
this.setUser(prop.get("User").toString());
this.setPassword(prop.get("Password").toString());
this.setSender(prop.get("Sender").toString());
this.setSubject(ExStr.CS(prop.get("Subject").toString()));

  Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);//设置smtp主机
properties.put("mail.smtp.auth", "true");//使用smtp身份验证
//获得邮件会话对象
Session session = Session.getDefaultInstance(properties,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, password);
}
});
//创建MIME邮件对象
MimeMessage mimeMsg = new MimeMessage(session);
if (sender != null)//设置发件人地址
{
mimeMsg.setFrom(new InternetAddress(sender));
}
if (receiver != null)//设置收件人地址
{
// mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver));
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(receiver,false));
}
if (subject != null)//设置邮件主题
{
mimeMsg.setSubject(subject, "GBK");
}
Multipart multipart = new MimeMultipart();
MimeBodyPart part = new MimeBodyPart();//mail内容部分
//setText method sets the given String as this part's content,
//with a MIME type of "text/plain"
part.setText(content == null ? "" : content, "GBK");
//设置邮件格式为html,并指定字符集,否则会是乱码
part.setContent(content.toString(),"text/html;charset=GBK");
multipart.addBodyPart(part); //在 Multipart 中增加HTML内容部分
String file1="E:\\EKing\\DevelopeLearning\\J2EE\\javamailTest\\attach1.txt";
String file2="E:\\EKing\\DevelopeLearning\\J2EE\\javamailTest\\attach2.txt";
String[] files = {file1,file2};
if (files != null && files.length > 0) { //邮件附件
for (int i = 0; i < files.length; i++) {
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds = new FileDataSource(files[i]);
mbp.setDataHandler(new DataHandler(fds));
try{
mbp.setFileName(MimeUtility.encodeWord(files[i], "GBK", null));
}catch(Exception e){}
multipart.addBodyPart(mbp);
}

}

mimeMsg.setContent(multipart); //增加 Multipart 到信息体
mimeMsg.setSentDate(new Date()); //设置发送日期
Transport.send(mimeMsg); //发送邮件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值