您的位置:首页 > 编程语言 > Java开发

使用javaMail发送邮件

2017-08-18 15:33 375 查看
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import java.util.Properties;

/**

* 需要mail.jar

* 需要对发送邮箱开启POP3/SMTP服务,并保存授权密码

* Created by hgc on 2017/8/18.

*/

public class AutoboxingAndUnboxing{

public static void main(String[] args) throws Exception {

String to =”xxx@qq.com”;// 收件人电子邮箱

String from = “xxxx@qq.com”;// 发件人电子邮箱

String host = “smtp.qq.com”;//指定发送邮件的主机为 smtp.qq.com,该主机为QQ 邮件服务器

Properties properties = System.getProperties(); // 获取系统属性

properties.setProperty(“mail.smtp.host”,host);// 设置邮件服务器

/**

* 关于QQ邮箱,还要设置SSL加密,加上以下代码即可

*/

properties.put(“mail.smtp.auth”, “true”);

MailSSLSocketFactory sf = new MailSSLSocketFactory();

sf.setTrustAllHosts(true);

properties.put(“mail.smtp.ssl.enable”, “true”);

properties.put(“mail.smtp.ssl.socketFactory”, sf);

Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("xxx@qq.com", "password"); //发件人邮件用户名、密码,使用的是授权密码
}
});

MimeMessage message = new MimeMessage(session);// 创建默认的 MimeMessage 对象
message.setFrom(new InternetAddress(from));// Set from: 头部头字段(正常邮箱发送中的发件人)
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set To: 头部头字段(正常邮箱发送中的收件人)
message.setSubject("This is the Subject Line!");// Set Subject: 头部头字段(正常邮箱发送的主题)
message.setText("This is actual message"); // 设置消息体(正常邮箱发送的正文)
Transport.send(message);// 发送消息
System.out.println("Sent message successfully....");
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  邮件