一、java mail发送邮件:
1.pom.xml
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
2.代码
2.1email实体类
@Data
public class EmailDto {
private String serverName;
private String port;
private String userName;
private String password;
private String senderName;
private String emailAddress;
private String subject;
private String to;
private String cC;
private String content;
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
2.2邮件发送
public class MailUtils {
public static void sendMail(EmailDto emailDto, JSONArray filePath) {
Transport transport = null;
try {
Properties prop = new Properties();
prop.setProperty("mail.host", emailDto.getServerName());
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailDto.getUserName(), emailDto.getPassword());
}
});
transport = session.getTransport();
transport.connect(emailDto.getServerName(), emailDto.getUserName(), emailDto.getPassword());
MimeMessage mimeMessage = getMimeMessage(session, emailDto, filePath);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
private static MimeMessage getMimeMessage(Session session, EmailDto emailDto, JSONArray filesPath) throws Exception {
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(emailDto.getEmailAddress()));
if (StringUtils.isNotBlank(emailDto.getTo())) {
String[] tos = emailDto.getTo().split(",");
for (String to : tos) {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
}
if (StringUtils.isNotBlank(emailDto.getCC())) {
String[] ccs = emailDto.getTo().split(",");
for (String cc : ccs) {
mimeMessage.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));
}
}
mimeMessage.setSubject(emailDto.getSubject());
MimeMultipart multipart = new MimeMultipart();
for (Object pathObj : filesPath) {
MimeBodyPart attachPart = new MimeBodyPart();
File file = new File((String) pathObj);
attachPart.setDataHandler(new DataHandler(new FileDataSource(file)));
attachPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachPart);
}
MimeBodyPart contentPart = new MimeBodyPart();
contentPart.setContent(emailDto.getContent(), "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
multipart.setSubType("mixed");
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
return mimeMessage;
}
}
二、spring自带的邮件发送器发送邮件
1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.代码
private static JavaMailSenderImpl createMailSender(EmailDto emailDto) {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(emailDto.getServerName());
sender.setPort(Integer.parseInt(emailDto.getPort()));
sender.setUsername(emailDto.getUserName());
sender.setPassword(emailDto.getPassword());
sender.setDefaultEncoding("Utf-8");
Properties p = new Properties();
p.setProperty("mail.smtp.timeout", "25000");
p.setProperty("mail.smtp.auth", "false");
sender.setJavaMailProperties(p);
return sender;
}
public void sendMail(EmailDto emailDto, MultipartFile... files) throws MessagingException, UnsupportedEncodingException {
long startTime = System.currentTimeMillis();
JavaMailSenderImpl mailSender = createMailSender(emailDto);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(emailDto.getEmailAddress(), emailDto.getSenderName());
messageHelper.setTo(emailDto.getTo().split(","));
messageHelper.setSubject(emailDto.getSubject());
messageHelper.setText(emailDto.getContent(), true);
if (StringUtils.isNotBlank(emailDto.getCC())) {
messageHelper.setCc(emailDto.getCC().split(","));
}
for (MultipartFile file : files) {
if (!file.isEmpty() && file.getOriginalFilename() != null) {
messageHelper.addAttachment(file.getOriginalFilename(), file);
}
}
mailSender.send(mimeMessage);
log.info("邮件发送耗时:" + (System.currentTimeMillis() - startTime) / 1000.0);
}
三、使用Apache commons-email发送html邮件
1.pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
2.代码
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import java.util.List;
public class MailUtil {
public static class EmailInfo {
private String mailServer;
private Integer mailPort;
private String mailNick;
private String mailUsername;
private String mailPassword;
private String title;
private String content;
private List<String> receivers;
boolean ssl;
public EmailInfo(String mailServer,Integer mailPort,String mailNick,String mailUsername,
String mailPassword,String title,String content,List<String> receivers,boolean ssl) {
this.mailServer = mailServer;
this.mailPort = mailPort;
this.mailNick = mailNick;
this.mailUsername = mailUsername;
this.mailPassword = mailPassword;
this.title = title;
this.content = content;
this.receivers = receivers;
this.ssl = ssl;
}
public MailUtil send() throws Exception {
return new MailUtil(this);
}
}
private MailUtil(EmailInfo emailInfo) throws Exception {
HtmlEmail email = new HtmlEmail();
email.setHostName(emailInfo.mailServer);
email.setSmtpPort(emailInfo.mailPort);
email.setAuthentication(emailInfo.mailUsername, emailInfo.mailPassword);
email.setStartTLSEnabled(false);
email.setSSLOnConnect(emailInfo.ssl);
try {
email.setFrom(emailInfo.mailUsername,emailInfo.mailNick);
int size = emailInfo.receivers.size();
email.addTo(emailInfo.receivers.toArray(new String[size]));
email.setCharset("UTF-8");
email.setDebug(false);
email.setSubject(emailInfo.title);
email.setHtmlMsg(emailInfo.content);
email.send();
System.out.println("邮件发送成功!");
} catch (EmailException e) {
System.out.println("邮件发送失败!");
throw new Exception(e);
}
}
}