介绍
发邮件mail是常见的软件功能,下面利于spring和java的mail库实现发送内容支持html,带多附件的案例
开启SMTP邮件发送协议
依赖
<!--Java MAil 发送邮件API-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
代码
package com.mail;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
* @version v1.0 创建时间:2023/11/20 15:59
* @author: 作者:陈子枢
* @web CSDN:https://blog.csdn.net/nutony
* @description 描述:读取属性配置文件,发送邮件
*/
@Slf4j
@PropertySource("classpath:mail.properties")
public class MailClient {
@Value("${host}")
private String minioUrl;
@Value("${port}")
private int port;
public static void sender(String form, String cc, String subject, String html, List<String> attachments) throws javax.mail.MessagingException {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("smtp.163.com");
sender.setPort(25);
sender.setUsername(form);
sender.setPassword("配置的授权码");
sender.setDefaultEncoding("UTF-8");
// 简化对mimeMessage的封装
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(sender.createMimeMessage(), true, "UTF-8");
helper.setFrom(sender.getUsername()); //邮件发送人
helper.setCc(cc); //抄送
helper.setSubject(subject); //标题
helper.setText(html,true); //正文
//邮件附件
for(String attachment: attachments) {
File file = new File(attachment);
helper.addAttachment(file.getName(), file);
}
sender.send(helper.getMimeMessage());
}
public static void main(String[] args) throws MessagingException, javax.mail.MessagingException {
List<String> attachments = new ArrayList<>();
attachments.add("d:\1.png");
attachments.add("d:\2.png");
MailClient.sender("13261758319@163.com", "52399178@qq.com", "HTML邮件", "<h1 style='color:red'>hello,world!</h1>",attachments);
log.info("邮件发送成功!");
}
}
原文地址:https://blog.csdn.net/nutony/article/details/134804849
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_47802.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。