邮件发送功能(可发送富文本和附件)

来源:csdn博客 分类: 文章浏览史 发布时间:2021-11-20 21:12:02 最后更新:2021-11-20 浏览:300
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2021-11-20 21:12:02

备注:用UrlResource可以直接将附件链接放到邮件里面,不用先下载

private final static String host = "****"; // smtp服务器
private final static String from = "******"; // smtp服务器
private final static String username = "*****"; // 邮箱名称
private final static String pwd = "*****"; // 邮箱密码

/**
* 发送富文本邮件
*
* @param agentSendEmailVO
*/
public static void richContentSend(AgentSendEmailVO agentSendEmailVO) {
try {
System.setProperty(“mail.mime.splitlongparameters”, “false”);
mailSender.setHost(host);
mailSender.setUsername(username);
mailSender.setPassword(pwd);
MimeMessage msg = mailSender.createMimeMessage();
//这个一定要加,否则富文本会出现中文乱码
MimeMessageHelper helper = new MimeMessageHelper(msg, true, “UTF-8”);
List emails = agentSendEmailVO.getEmails();
if (!CollectionUtils.isEmpty(emails)) {
String[] emailArray = new String[emails.size()];
for (int i = 0; i < emails.size(); i++) {
emailArray[i] = emails.get(i);
}
helper.setFrom(from);
helper.setTo(emailArray);
helper.setSubject(agentSendEmailVO.getSubject());
//第二个参数true,表示text的内容为html,然后注意标签,src=‘cid:file’,'cid’是contentId的缩写,'file’是一个标记,需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件
helper.setText(agentSendEmailVO.getContent(), true);
if (!CollectionUtils.isEmpty(agentSendEmailVO.getAttachVOS())) {
//加载文件资源,作为附件
//加入附件
try {
for (int i = 0; i < agentSendEmailVO.getAttachVOS().size(); i++) {
if (!StringUtils.isEmpty(agentSendEmailVO.getAttachVOS().get(i).getUrl())) {
UrlResource urlResource = null;
urlResource = new UrlResource(agentSendEmailVO.getAttachVOS().get(i).getUrl());
helper.addAttachment(MimeUtility.encodeWord(agentSendEmailVO.getAttachVOS().get(i).getAttachName(), “UTF-8”, “B”), urlResource);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}

            }
            mailSender.send(msg);
            log.info("===========================开始发送邮件结束================================= ");
        }
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}
php技术微信