关于java发送邮件用例
一直想写个java发送邮件的实例,这次总算有机会了,废话不多说,下面看详情!!!!
本次实例用的是qq邮箱
1:下载两个jar包,加入java工程
2:java发送邮件属于第三方登录需要密码认证,通过生成授权码来实现邮件密码发送
3:代码
public class MailTest {
public static void main(String[] args) {
// 收件人
String to = "收件人邮箱";
// 发件人
String from = "发件人邮箱@qq.com";
// 指定发送邮件的主机为 localhost
String host = "smtp.qq.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
try {
//接口ssl认证问题
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 获取默认session对象
// Session session = Session.getDefaultInstance(properties);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "第二步中生成的授权码"); // 发件人邮件用户名、密码
}
});
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject("邮件标题");
// 设置消息体
message.setText("邮件内容");
// 发送消息
Transport.send(message);
System.out.println("发送成功....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}