Java-邮件发送工具

POM配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.3.7.RELEASE</version>
</dependency>

示例代码

// 基本参数
String host = "smtp.xxx.xxxx.com";
int port = 234;
String username = "abc@xxx.xxxx.com";
String password = "abc@password";
String aliasName = "abc";

// to
String toMailUser = "bcd@xxx.xxxx.com";

// 附件
String path = "/data/file1";
File file = new File(path);

// 主题与正文
String subject = "这是一封测试邮件";
String text = "这是一封测试邮件-正文";

// 附件名称的参数|附件携带时必须参数
System.setProperty("mail.mime.splitlongparameters", "false");
// 创建发生器
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setProtocol("smtps");
mailSender.setUsername(username);
mailSender.setPassword(password);
mailSender.setDefaultEncoding("UTF-8");
Properties properties = new Properties();
properties.setProperty("mail.smtp.timeout", "15000");
properties.setProperty("mail.smtp.auth", "true");
mailSender.setJavaMailProperties(properties);

// 邮件内容设置
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
// 邮件发送者
messageHelper.setFrom(username, aliasName);
// 邮件接受者
messageHelper.setTo(username);
messageHelper.setCc(toMailUser);
// 邮件主题
messageHelper.setSubject(subject);
// 邮件正文
messageHelper.setText(text, true);
// 邮件携带附件
messageHelper.addAttachment(MimeUtility.encodeWord(file.getName(), "utf-8","B"), file);
// 发送邮件
mailSender.send(mimeMessage);

System.err.println("Over... ");
上一篇:Springboot-设置上传文件大小与不安全的HTTP方法


下一篇:Hadoop-HDFS的DataNode工作机制