1. 测试方法 当前对接的是谷歌邮箱
@org.junit.jupiter.api.Test
public void sendEmail (){
final String subject = "吃饭";//标题
final String username = "wqeqweqwe@gmail.com";//发件人邮箱
final String password = "sasdasdasdasd";//发件人专用密码
final String sname = "cccccccccc@gmail.com";//收件人邮箱
final String body = "今天你吃饭了吗";//内容
List<SFile>urlList =new ArrayList<>();
SFile sFile = new SFile();
sFile.setSendUrl("http://aaaaaaaaaaaaaaa:80/file/deng.png");
sFile.setSendName("附件名称");
urlList.add(sFile);
emailSender.sendEmail(username,password,sname,subject,body, urlList);
}
2.发件Utils
public void sendEmail(String username,String password,String to, String subject, String body, List<SFile> attachmentPath) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));// 接收者邮箱地址
message.setSubject(subject);// 邮件主题
// message.setText(body);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
if (attachmentPath != null && !attachmentPath.isEmpty()) {
for (SFile urls : attachmentPath) {
// 第一个附件
MimeBodyPart attachmentPart = new MimeBodyPart();
URL url = new URL(urls.getSendUrl());
URLConnection urlConnection = url.openConnection();
DataSource source = new URLDataSource(url);
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(urls.getSendName());
multipart.addBodyPart(attachmentPart);
}
}
// Create Multipart and add parts to it
// Set the content of the message to the multipart object
message.setContent(multipart);
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
throw new RuntimeException("网络异常,请稍后重试");
} catch (MalformedURLException e) {
throw new RuntimeException("网络异常,请稍后重试");
} catch (IOException e) {
throw new RuntimeException("网络异常,请稍后重试");
}
}