![cover](http://image.wzoe.fun/i/2024/06/10/6666cdf6952d2.png)
java 邮件发送(支持添加附件)
AI-摘要
佐伊 GPT
AI初始化中...
介绍自己
生成本文简介
推荐相关文章
前往主页
前往tianli博客
spring集成
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
#email
spring.mail.from=${spring.mail.from}
spring.mail.host=${spring.mail.host}
spring.mail.port=${spring.mail.port}
spring.mail.username=${spring.mail.username}
spring.mail.password=${spring.mail.password}
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
@Value("${spring.mail.from:roshan@pwrd.com}")
private String from;
private final JavaMailSender javaMailSender;
public void mail(String content, String title, List<String> users, List<File> files) {
if (CollectionUtils.isEmpty(users)) {
return;
}
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
mimeMessage.setSubject(title);
mimeMessage.setRecipients(Message.RecipientType.TO, String.join(",", users));
mimeMessage.setFrom(from);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(content, "text/html;charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
//附件
if (!CollectionUtils.isEmpty(files)) {
//关键代码:发送附件
for (File file : files) {
MimeBodyPart appendix = new MimeBodyPart();
appendix.setDataHandler(new DataHandler(new FileDataSource(file.getAbsolutePath())));
appendix.setFileName(file.getName());
multipart.addBodyPart(appendix);
}
}
mimeMessage.setContent(multipart);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error("邮件发送失败,收件人:{},title:{}", users, title, e);
}
}
public void mail(String content, String title, List<String> users) {
if (CollectionUtils.isEmpty(users)) {
return;
}
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(title);
helper.setFrom(from);
helper.setTo(users.toArray(new String[]{}));
helper.setSentDate(new Date());
helper.setText(content, true);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error("邮件发送失败,收件人:{},title:{}", users, title, e);
}
}
}
静态工具类
package com.zoe.person;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.UUID;
/**
* @author: zoe
*/
@Data
@Slf4j
@Accessors(chain = true)
public class SmtpMailUtil {
private MailSender mailSender;
private String form;
private String[] to;
private String text;
private String subject;
private BodyType bodyType = BodyType.TEXT;
private Path[] outlineAttachments;
private Path[] inlineAttachments;
public static MailSender createSimpleSender(String host, Integer port, String username, String password) {
MailSender mailSender = new MailSender();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
return mailSender;
}
public void send() throws SmtpMailException {
try {
MimeMessage mimeMessage = toMimeMessage();
mailSender.send(mimeMessage);
} catch (Throwable e) {
throw new SmtpMailException("SendMail_Is_Failed", e);
}
}
protected MimeMessage toMimeMessage() throws Exception {
if (mailSender == null) {
throw new Exception("mail sender cannot empty");
}
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
helper.setFrom(form);
helper.setTo(to);
helper.setSubject(subject);
StringBuilder content = new StringBuilder(text);
if (ArrayUtils.isNotEmpty(inlineAttachments)) {
setBodyType(BodyType.HTML);
for (Path inlineAttachment : inlineAttachments) {
String uuid = UUID.randomUUID().toString();
uuid = inlineAttachment.getFileName() + "@" + uuid;
FileSystemResource fileSystemResource = new FileSystemResource(inlineAttachment.toFile());
helper.addInline(uuid, fileSystemResource);
content.append("</br> <img src=\"cid:{CID}\">".replace("{CID}", uuid));
}
inlineAttachments = null;
}
if (ArrayUtils.isNotEmpty(outlineAttachments)) {
for (Path outlineAttachment : outlineAttachments) {
FileSystemResource fileSystemResource = new FileSystemResource(outlineAttachment.toFile());
helper.addAttachment(outlineAttachment.getFileName().toString(), fileSystemResource);
}
outlineAttachments = null;
}
if (BodyType.HTML.equals(bodyType)) {
helper.setText(content.toString(), true);
} else {
helper.setText(content.toString());
}
return mimeMessage;
}
public SmtpMailUtil setTo(String to) {
this.to = new String[]{to};
return this;
}
public SmtpMailUtil setTo(String[] to) {
this.to = to;
return this;
}
public static class MailSender extends JavaMailSenderImpl {
public MailSender() {
super();
}
@Override
public String toString() {
return "{" + "host:" + getHost() + "," +
"port:" + getPort() + "," +
"username:" + getUsername() + "," +
"password" + getPassword() +
"}";
}
}
public enum BodyType {
TEXT,
HTML;
BodyType() {
}
}
public static class SmtpMailException extends Exception {
public SmtpMailException(String message, Throwable cause) {
super(message, cause);
}
}
}
调用示例
package com.zoe.person;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import static javax.mail.Message.RecipientType.TO;
/**
* @author zoe
* @date 2024/6/10 15:16
*/
public class MailTest {
public static final String MAIL_SENDER = "xxx@qq.com";
public static final String MAIL_TO = "xxx@qq.com";
public static final String MAIL_USERNAME = MAIL_SENDER;
public static final String MAIL_PASSWORD = "xxx";
public static final String FILE_NAME = "/test/test.pdf";
public static final String HOST = "stmp.qq.com";
public static void main(String[] args) throws SmtpMailUtil.SmtpMailException, MessagingException {
MailTest mailTest = new MailTest();
mailTest.smtp1();
mailTest.smtpAttach();
mailTest.smtpHtml();
mailTest.smtpInline();
}
/**
* 单行邮件
*/
public void smtpInline() throws MessagingException {
SmtpMailUtil mailUtil = initSmtpMailUtil();
MimeMessage mimeMessage = mailUtil.getMailSender().createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
helper.setFrom(MAIL_SENDER);
helper.setTo(MAIL_TO);
// helper.setCc(cc);
// helper.setBcc(bcc);
helper.setSubject("MimeMessageHelper附件测试!");
helper.setText("<html><body><h4><font color='red'>这是一张内嵌图片</font>" +
"</h4><img src='cid:pic'/></body></html>", true);
FileSystemResource fileSystemResource = new FileSystemResource("/Users/wangzhao/Pictures/封面/6665758638cd8.png");
helper.addInline("pic", fileSystemResource);
mailUtil.getMailSender().send(mimeMessage);
}
/**
* 附件邮件
*/
public void smtpAttach() throws MessagingException {
SmtpMailUtil mailUtil = initSmtpMailUtil();
MimeMessage mimeMessage = mailUtil.getMailSender().createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
helper.setFrom(MAIL_SENDER);
helper.setTo(MAIL_TO);
// helper.setCc(cc);
// helper.setBcc(bcc);
helper.setSubject("附件测试!");
//设置正文
helper.setText("<p>您好:</p><p>详情见附件</p><p></p>", true);
//附件
FileSystemResource fileSystemResource = new FileSystemResource(FILE_NAME);
//添加附件名和附件输入流
helper.addAttachment("接口文档.pdf", fileSystemResource);
mailUtil.getMailSender().send(mimeMessage);
}
/**
* HTML邮件
*/
public void smtpHtml() {
SmtpMailUtil mailUtil = initSmtpMailUtil();
MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
//设置发信人
mimeMessage.setFrom(new InternetAddress(MAIL_SENDER));
//设置收信人,可以设置多个,采用参数数组或者","分隔
mimeMessage.addRecipients(TO, MAIL_TO);
//设置抄送人,可以设置多个,采用参数数组或者","分隔
// mimeMessage.addRecipients(CC, cc);
//设置暗送人,可以设置多个,采用参数数组或者","分隔
// mimeMessage.addRecipients(BCC, bcc);
//设置邮件主题(标题)
mimeMessage.setSubject("mimeMessagePreparator的HTML邮件");
//设置邮件内容(正文)和类型
mimeMessage.setContent("<p>您好:</p><p>测试内容1</p><p>至此</p>", "text/html;charset =utf-8");
};
mailUtil.getMailSender().send(mimeMessagePreparator);
}
/**
* 简单邮件
*/
public void smtp1() throws SmtpMailUtil.SmtpMailException {
SmtpMailUtil mailUtil = initSmtpMailUtil();
mailUtil.setForm(MAIL_SENDER);
mailUtil.setTo(new String[]{MAIL_TO});
mailUtil.setSubject("测试1");
mailUtil.setText("<p>您好:</p><p>测试内容1</p><p>至此</p>");
mailUtil.send();
}
/**
* 初始化邮件工具
*/
protected SmtpMailUtil initSmtpMailUtil() {
SmtpMailUtil mailUtil = new SmtpMailUtil();
SmtpMailUtil.MailSender mailSender = SmtpMailUtil.createSimpleSender(HOST, 25, MAIL_SENDER, MAIL_PASSWORD);
mailUtil.setMailSender(mailSender).setForm(MAIL_SENDER);
return mailUtil;
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员佐伊
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果