原创

【JAVA】基于SMTP发送邮件遇到的问题

前言

公司要做一个授权提醒的小程序,记录哪些运维系统的授权将要到期,提醒对应的人员进行授权的更新。

代码

package com.ruoyi.project.system.LicenseContent.task;

import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.web.service.ConfigService;

@Component
public class MailHelper {


    @Autowired
    private ConfigService configService;

    private JavaMailSenderImpl mailSender;

    public MailSender sendMailToNotifyUser() {

        String license_mail_host = Convert.toStr(configService.getKey("license.mail.host"));
        String license_mail_port = Convert.toStr(configService.getKey("license.mail.port"));
        String license_mail_user = Convert.toStr(configService.getKey("license.mail.user"));
        String license_mail_pwd = Convert.toStr(configService.getKey("license.mail.pwd"));

        System.setProperty("java.net.preferIPv4Stack", "true");

        mailSender = new JavaMailSenderImpl();
        mailSender.setHost(license_mail_host);// 指定用来发送Email的邮件服务器主机名
        // mailSender.setPort(465);//默认端口,标准的SMTP端口
        mailSender.setUsername(license_mail_user);// 用户名
        mailSender.setPassword(license_mail_pwd);// 密码

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");// 开启认证
        properties.setProperty("mail.debug", "true");// 启用调试
        properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
        properties.setProperty("mail.smtp.port", license_mail_port);// 设置端口
        properties.setProperty("mail.smtp.socketFactory.port", license_mail_port);// 设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        // properties.setProperty("mail.smtp.socketFactory.class",
        // "javax.net.ssl.SSLSocketFactory");
        mailSender.setJavaMailProperties(properties);

        return mailSender;

    }

    public static void main(String[] args) {
        // sendSimpleEmail();
    }

    public void sendSimpleEmail(String from, String to, String subject, String text, String cc) {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper;
        try {
            mimeMessageHelper = new MimeMessageHelper(message, true);
            // 邮件发送人
            mimeMessageHelper.setFrom(from);
            // 邮件接收人
            mimeMessageHelper.setTo(to);
            // 邮件主题
            mimeMessageHelper.setSubject(subject);

            // 邮件内容,HTML格式
            //mimeMessageHelper.setText(text);
            //mimeMessageHelper.setText(text);
            //mimeMessageHelper.setText(text,true);
            message.setContent(text,"text/html ;charset=utf-8");

            if(cc!=null && cc.split(";").length>0) {
                mimeMessageHelper.setCc(cc.split(";"));
            }

            mailSender.send(message);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("邮件发送完毕");
    }
}
package com.ruoyi.project.system.LicenseContent.task;

import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtilsOfWeek;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.project.system.LicenseContent.domain.LicenseContent;
import com.ruoyi.project.system.LicenseContent.service.ILicenseContentService;
import com.ruoyi.project.system.LicenseContent.service.impl.LicenseContentServiceImpl;
import com.ruoyi.project.tool.gen.util.VelocityInitializer;

@Component("autoJob")
@EnableScheduling
public class AutoJob {

    @Autowired
    private ILicenseContentService licenseContentService;

    @Autowired
    private ConfigService configService;
    @Autowired
    private MailHelper mailHelper;
    //每天1点执行
    @Scheduled(cron = "0,30 * * * * ?")
    public void sendMailToNotifyUser() {
        System.out.println("sendMailToNotifyUser");
        LicenseContent licenseContent=new LicenseContent();
        HashMap<String, Object> params=new HashMap<String, Object>();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        String lastTwoMonths = df.format(DateUtilsOfWeek.getLastTwoMonthsDate());

        params.put("beginLicenseExpirDate", lastTwoMonths);
        params.put("endLicenseExpirDate", df.format(new Date()));
        licenseContent.setParams(params);
        List<LicenseContent>  list=licenseContentService.selectLicenseContentList(licenseContent);

        if(list==null || list.size()==0) {
            return ;
        }

        mailHelper.sendMailToNotifyUser();

        list.forEach(w->{

            mailHelper.sendSimpleEmail(Convert.toStr(configService.getKey("license.mail.user")),w.getLicenseContactEmail(), w.getLicenseName(), getMsgContent(w),w.getLicenseContactEmailCc());

            System.out.println(w.getLicenseName());
        });
    }
    private String getMsgContent(LicenseContent lc) {

        VelocityInitializer.initVelocity();

        Template tpl = Velocity.getTemplate("vm/html/mail.html.vm", Constants.UTF8);
        // 渲染模板
        StringWriter sw = new StringWriter();
        VelocityContext context=new VelocityContext();
        context.put("licenseContent", lc);
        tpl.merge(context, sw);
        String retSw=sw.toString();

        return retSw;
    }
}

问题

1. 发送邮件后,显示SSL报错

DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "mail.xxx.com", port 465, isSSL false
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: mail.xxx.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: mail.xxx.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?; message exception details (1) are:
Failed message 1:

是因为代码中包含了properties.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");,而邮箱服务器没有正确的SSL证书导致,先屏蔽了

2. html格式的数据,显示为纯文本

设置文本的时候,指定为超文本即可。


// 邮件内容,HTML格式
//mimeMessageHelper.setText(text);
mimeMessageHelper.setText(text,true);

3. 收件人收到的内容为问号(?)

由于编码问题导致,调整代码如下:

//mimeMessageHelper.setText(text);
//mimeMessageHelper.setText(text,true);
message.setContent(text,"text/html ;charset=utf-8");

本文来自:【JAVA】基于SMTP发送邮件遇到的问题-小码农,转载请保留本条链接,感谢!

温馨提示:
本文最后更新于 2023年03月05日,已超过 448 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
正文到此结束
本文目录