java实现发送邮件

项目准备:javax.mail-1.5.4.jar
一个邮箱此处以@163邮箱为例子
(设置如图1.2)
图1.2
代码如下:
public static void sendMail(MailMsgBean mail, String project_name, YN_FLAG flag) {

    logger.info("邮件发送-------->>to:[{}]“,mail.getTarget_mail());
    //发送人
    final String from = mail.getHost_mail().trim();
    //发送协议类型:此处用的是smtf
    String host = mail.getHost_type().trim();
    //授权密码
    final String pwd = mail.getHost_pwd().trim();
    //邮件内容
    String msg = mail.getContent_mail();
    //收件人
    String to = mail.getTarget_mail();


     //激活协议
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.auth", "true");

    try {
        // QQ邮箱特殊处理
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, pwd);
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("邮件主题");

        //String body = new String(content.getBytes("iso-8859-1"),"utf-8");
        String msg = "<html><head></head><body>" +content+"</body></html>"
        //此处以发送html形式为例(可以以纯文本发送)
        message.setContent(msg, "text/html;charset=gb2312");
        //发送
        if(!Assert.isEmpty(to)){
            Transport.send(message);
        }
        logger.info("邮件发送完成!");
    } catch (Exception e) {

        e.printStackTrace();
        logger.info("邮件发送error!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值