JavaMail

由于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();
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值