用java程序发送邮件

发送没有附件的邮箱:

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);
}

posted @ 2016-05-16 15:53  无名可起  阅读(495)  评论(1编辑  收藏  举报