JavaMail

来源:互联网 发布:dns的协议端口号 编辑:程序博客网 时间:2024/06/04 18:42

由于JAVAMail需要和服务器进行通信,这就要求程序提供一些相关信息,JAVAMail可以通过Properties封装

–Properties

Properties pros = new Properties();props.put("mail.smtp.host","smtp.sina.com.cn");props.put("mail.smtp.auth","true");

mail.stmp.host SMTP服务器地址,如smtp.sina.com.cn
mail.stmp.auth SMTP服务器是否需要用户认证

–Session
创建Session对象,接受Properties设置的属性信息,初始化JAVAMail配置,创建一个邮件处理环境

Session session = Session.getInstance(props) 根据props属性创建一个新的Session实例,未使用安全认证信息

–创建好Session就可创建要发送的内容,由Message完成

MimeMessage msg = new MimeMessage(session);msg.setSubject("标题");msg.setText("内容");

–创建好Message就准备发送地址
msg.setFrom(new InternetAddress(“我的邮箱地址”))

–弄好地址就准备发送
JavaMail邮件是利用了Transport,而Transport是由Session提供的,session是利用ggetTransport重载方法来设置属性。

Transport transport = session.getTransport();

–建立连接

transport.connection("邮件host","账号","密码");

–发送

 transport.sendMessage (msg, new Address[] { new InternetAddress("发送账号") });

–关闭

 transport.close();

–由于现在的都需要SSL加密,所以

    MailSSLSocketFactory ssl = new MailSSLSocketFactory();    ssl.setTrustAllHosts(true);    props.put("mail.smtp.ssl.enable", "true");    props.put("mail.smtp.ssl.socketFactory", ssl);
public class MailTool {  public static void main(String[] args) throws MessagingException, GeneralSecurityException {    //配置文件    Properties props = new Properties();    //SSL加密    MailSSLSocketFactory ssl = new MailSSLSocketFactory();    ssl.setTrustAllHosts(true);    props.put("mail.smtp.ssl.enable", "true");    props.put("mail.smtp.ssl.socketFactory", sf);    //    Session session = Session.getInstance(props);    Message msg = new MimeMessage(session);    msg.setSubject("标题");    msg.setText("测试11");    msg.setFrom(new InternetAddress("我的邮箱"));    Transport transport = session.getTransport();    //连接    transport.connect("smtp.qq.com", "我的邮箱账号", "密码");    //发送    transport.sendMessage (msg, new Address[] { new InternetAddress("收件邮箱") });    transport.close();  }}
0 0
原创粉丝点击