| | |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.stereotype.Service; |
| | | import javax.mail.MessagingException; |
| | | import javax.mail.internet.InternetAddress; |
| | | import javax.mail.internet.MimeMessage; |
| | | import javax.mail.internet.MimeUtility; |
| | | import java.io.File; |
| | | import java.io.UnsupportedEncodingException; |
| | | |
| | | @Component |
| | | public class EmailUtil { |
| | |
| | | this.javaMailSender = javaMailSender; |
| | | } |
| | | |
| | | public void sendEmailWithAttachment(String to, String subject, String text, File attachment) throws MessagingException { |
| | | public void sendEmailWithAttachment(String to, String subject, String text, File attachment,String displayFileName) throws MessagingException, UnsupportedEncodingException { |
| | | MimeMessage message = javaMailSender.createMimeMessage(); |
| | | MimeMessageHelper helper = new MimeMessageHelper(message, true); |
| | | |
| | | // 设置发件人(必须与配置的spring.mail.username一致) |
| | | helper.setFrom(fromEmail); |
| | | String nick=""; |
| | | try { |
| | | nick=javax.mail.internet.MimeUtility.encodeText("贵人家园出行"); |
| | | } catch (UnsupportedEncodingException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | // 设置发件人 |
| | | helper.setFrom(new InternetAddress(nick + " <" + fromEmail + ">")); |
| | | // 设置收件人 |
| | | helper.setTo(to); |
| | | // 设置邮件主题和内容 |
| | | helper.setSubject(subject); |
| | | helper.setText(text); |
| | | // 添加附件 |
| | | helper.addAttachment(attachment.getName(), attachment); |
| | | if(null != attachment){ |
| | | // 使用显示文件名而非原文件名 |
| | | helper.addAttachment( |
| | | MimeUtility.encodeWord(displayFileName), // 编码避免中文乱码 |
| | | attachment |
| | | ); |
| | | } |
| | | |
| | | |
| | | // 发送邮件 |
| | | javaMailSender.send(message); |