码迷,mamicode.com
首页 > 编程语言 > 详细

用java程序发送邮件

时间:2016-05-16 17:16:35      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

发送没有附件的邮箱:

public void test2() throws Exception{
//1:声明服务器地址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定服务器,以搜狐邮箱为例
p.setProperty("mail.smtp.auth","true");//进行验证
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxx","密码");
}
};
//2:声明Session
Session session = Session.getDefaultInstance(p,auth);
//设置为调试模式
session.setDebug(true);
//3:声明信息
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxxxxx@sohu.com"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要发送的邮箱"));
msg.setSubject("标题,谁便");
msg.setContent("内容,自己写","text/html;charset=UTF-8");
//发送
Transport.send(msg);
}

发送含有附件的邮件:

public void test3() throws Exception{
//1:声明服务器地址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定服务器,以搜狐为例
p.setProperty("mail.smtp.auth","true");//进行验证
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx","密码");
}
};
//2:声明Session
Session session = Session.getDefaultInstance(p,auth);
//设置为调试模式
session.setDebug(true);
//3:声明信息
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxxxxxx@sohu.com"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要发送的邮箱"));
msg.setSubject("大家好1111");

//声明Multibody
MimeMultipart multi = new MimeMultipart();
//添加一个附件
javax.mail.internet.MimeBodyPart part1 = new javax.mail.internet.MimeBodyPart();
part1.attachFile(new File("文件的地址"));
part1.setFileName(MimeUtility.encodeText("要发送的文件名及后缀"));
multi.addBodyPart(part1);
javax.mail.internet.MimeBodyPart part2 = new javax.mail.internet.MimeBodyPart();
part2.setContent("你好这是内容<b>Hello</b>","text/html;charset=UTF-8");

multi.addBodyPart(part2);

msg.setContent(multi);


Transport.send(msg);
}

用java程序发送邮件

标签:

原文地址:http://www.cnblogs.com/nuoya/p/5498359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!