基于feign传参MultipartFile问题解决
326
2022-08-06
基于Java实现简单的邮件群发功能(java实现邮件发送功能代码)
目录pom文件引入第三方依赖java代码如下运行测试
pom文件引入第三方依赖
java代码如下
import lombok.Data;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by tarzan liu on 2021/5/9.
*/
public abstract class EmailUtil {
private static final Session session;
private static final EmailAuthenticator authenticator;
static {
InputStream inputStream = null;
try {
inputStream = EmailUtil.class.getResourceAsStream("/email.properties");
Properties properties = new Properties();
properties.load(inputStream);
authenticator = new EmailAuthenticator();
String username = properties.getProperty("email.username");
authenticator.setUsername(username);
String password = properties.getProperty("email.password");
authenticator.setPassword(password);
String smtpHostName = "smtp." + username.split("@")[1];
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", smtpHostName);
sesshttp://ion = Session.getInstance(properties, authenticator);
} catch (Exception e) {
throw new RuntimeException("init error.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private EmailUtil() { }
/**
* 群发邮件方法
*/
private static void massSend(List
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(authenticator.getUsername()));
InternetAddress[] addresses = new InternetAddress[recipients.size()];
for (int index = 0; index < recipients.size(); index ++) {
addresses[index] = new InternetAddress(recipients.get(index));
}
message.setRecipients(RecipientType.TO, addresses);
message.setSubject(email.getSubject());
message.setContent(email.getContent(), "text/html;charset=utf-8");
Transport.send(message);
}
/**
* 发送邮件
*/
public static void send(String recipient, SimpleEmail email) throws MessagingException {
List
recipients.add(recipient);
massSend(recipients, email);
}
//可以单独建一个类
@Data
public static class SimpleEmail {
private String subject;
private String content;
}
public static void main(String[] args) throws Exception {
SimpleEmail simpleEmail = new SimpleEmail();
simpleEmail.setSubject("今天你学习了么?");
simpleEmail.setContent("今天你写博客了么");
send("1334512682@qq.com", simpleEmail);
}
}
email.properties 系统邮箱配置
email.username=###@163.comemail.password=###
你的邮箱账号和密码,也可以省去配置文件,直接把账号密码写死在代码。
运行测试
右键run 运行主方法。
将发送的邮箱绑定到微信上,还能实现微信提醒功能!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~