用Java写一个异步邮件发送
时间: 2023-01-11 13:55:36 浏览: 129
可以使用JavaMail API来实现异步邮件发送。
首先,需要在项目中引入JavaMail依赖,然后使用如下代码发送邮件:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncEmailSender {
private static final String SMTP_HOST = "smtp.gmail.com"; //SMTP服务器地址
private static final String FROM_ADDRESS = "you@gmail.com"; //发件人地址
private static final String FROM_PASSWORD = "yourpassword"; //发件人密码
private static final ExecutorService executorService = Executors.newFixedThreadPool(5); //创建线程池
public static void sendEmail(String toAddress, String subject, String content) {
executorService.submit(() -> { //提交线程任务
try {
//创建Properties对象
Properties properties = new Properties();
//设置发送邮件的主机SMTP
properties.setProperty("mail.smtp.host", SMTP_HOST);
//设置验证机制
properties.setProperty("mail.smtp.auth", "true");
//创建Session对象
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD); //发件人邮箱和密码
}
});
//创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
//设置发件人
message.setFrom(new InternetAddress(FROM_ADDRESS));
//设置收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
//设置邮件主题
message.setSubject(subject);
//设置邮件正文
message.setContent(content, "text/html;charset=UTF-8");
//发送邮件
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
});
}
阅读全文