java邮件工具(Java邮件发送带附件)
1、引入发送邮件依赖<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
,我来为大家科普一下关于java邮件工具?以下内容希望对你有帮助!
java邮件工具
1、引入发送邮件依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2、邮件发送工具类
参数说明:smtpHost:邮箱服务器,如 smtp.qq.compassword:授权码fromMail:发件人邮箱toMail:收件人邮箱title:邮件标题content:邮件内容filePath:附件路径
@Component
public class MailPublish {
private static void send(String smtpHost, String password, String fromMail, String toMail, String title, String content, String filePath) throws Exception {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", smtpHost);
props.setProperty("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromMail, password);
}
};
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toMail));
message.setSubject(title);
// 邮件正文
MimeBodyPart body = new MimeBodyPart();
body.setContent(content, "text/html;charset=utf-8");
// 准备附件
DataSource source = new FileDataSource(new File(filePath));
DataHandler handler = new DataHandler(source);
// 添加附件
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(handler);
attachment.setFileName(MimeUtility.encodeText(handler.getName()));
// 将正文和附件放入multipart
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachment);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
路漫漫其修远兮,吾将上下而求索
译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。
如果您有什么好的想法与方法,欢迎在评论区留言,我们一起讨论~
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com