Mail 发邮件

Mail类

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.smtp.SMTPTransport;

public class Mail {
private final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private String host=null;
private int port=25;
private String auth=null;
private String username=null;
private String password=null;
private boolean mailusername=false;
private Session session = null;
ThreadPoolExecutor executor = null;
{
executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60,TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
}
public Mail(Map<String,String> mails) {
this.host=mails.get("server");
int tempPort=Common.toDigit(mails.get("port"));
if(tempPort>0){
this.port=tempPort;
}
this.auth=mails.get("auth");
this.username=mails.get("auth_username");
this.password=mails.get("auth_password");
if("1".equals(mails.get("mailusername"))){
this.mailusername=true;
}
}
public Mail(String host,int port,String auth,String username,String password,String mailusername) {
this.host=host;
if(port>0){
this.port=port;
}
this.auth=auth;
this.username=username;
this.password=password;
if("1".equals(mailusername)){
this.mailusername=true;
}
}

private synchronized void createSession() {
Properties mailProps = new Properties();
mailProps.setProperty("mail.transport.protocol", "smtp");
mailProps.setProperty("mail.smtp.host", host);
mailProps.setProperty("mail.smtp.port", String.valueOf(port));
if("smtp.gmail.com".equals(host)){
mailProps.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
mailProps.setProperty("mail.smtp.socketFactory.fallback", "false");
mailProps.setProperty("mail.smtp.socketFactory.port",String.valueOf(port));
}
if ("1".equals(auth)) {
mailProps.put("mail.smtp.auth", "true");
}
session = Session.getDefaultInstance(mailProps,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}

private MimeMessage createMimeMessage() {
if (session == null) {
createSession();
}
return new MimeMessage(session);
}

public String sendMessage(String from,String toEmail,String subject, String textBody, String htmlBody) {
String result=null;
try {
String encoding = MimeUtility.mimeCharset(JspRunConfig.CHARSET);
MimeMessage message = createMimeMessage();
String toEmails[] = toEmail.split(",");
Address to[] = new Address[toEmails.length];
for (int i = 0; i < toEmails.length; i++) {
String sTo=toEmails[i];
if(sTo.matches("^.*<.*>$")){
int index=sTo.indexOf("<");
to[i] = new InternetAddress(sTo.substring(index+1,sTo.length()-1),mailusername?sTo.substring(0, index):"", encoding);
}else{
to[i] = new InternetAddress(sTo, "", encoding);
}
}
String fromName=null;
String fromEmail;
if(from.matches("^.*<.*>$")){
int index=from.indexOf("<");
if(mailusername){
fromName=from.substring(0, index);
}
fromEmail=from.substring(index+1,from.length()-1);
}else{
fromEmail=from;
}
Address fromAddress = new InternetAddress(fromEmail,fromName!=null?fromName:"", encoding);

message.setHeader("Date", Common.gmdate("EEE, dd MMM yyyy HH:mm:ss Z", (int)(System.currentTimeMillis()/1000), "0"));
message.setHeader("Content-Transfer-Encoding", "8bit");
message.setRecipients(Message.RecipientType.TO, to);
message.setFrom(fromAddress);
message.setSubject(subject, encoding);
MimeMultipart content = new MimeMultipart("alternative");
if (textBody != null && htmlBody != null) {
MimeBodyPart text = new MimeBodyPart();
text.setText(textBody, encoding);
text.setDisposition(Part.INLINE);
content.addBodyPart(text);
MimeBodyPart html = new MimeBodyPart();
html.setContent(htmlBody, "text/html;charset="+encoding);
html.setDisposition(Part.INLINE);
content.addBodyPart(html);
} else if (textBody != null) {
MimeBodyPart text = new MimeBodyPart();
text.setText(textBody, encoding);
text.setDisposition(Part.INLINE);
content.addBodyPart(text);
} else if (htmlBody != null) {
MimeBodyPart html = new MimeBodyPart();
html.setContent(htmlBody, "text/html;charset="+encoding);
html.setDisposition(Part.INLINE);
content.addBodyPart(html);
}
message.setContent(content);
message.setDisposition(Part.INLINE);
addToTask(message);
} catch (Exception e) {
result=e.getMessage();
}
return result;
}

private void addToTask(MimeMessage message) {
if (message != null) {
sendMessages(Collections.singletonList(message));
} else {
System.out.println("Cannot add null email message to queue.");
}

}

private void sendMessages(Collection<MimeMessage> messages) {
if (messages.size() == 0) {
return;
}
executor.execute(new EmailTask(messages));
}

private class EmailTask implements Runnable {
private Collection<MimeMessage> messages;
public EmailTask(Collection<MimeMessage> messages) {
this.messages = messages;
}
public void run() {
try {
sendMessages();
} catch (MessagingException me) {
int timestamp =(int)(System.currentTimeMillis()/1000);
Log.writelog("errorlog", timestamp, timestamp+"\tSMTP\t\t("+host+":"+port+") CONNECT - Unable to connect to the SMTP server");
}
}
public boolean sendMessages() throws MessagingException {
Transport transport = null;
try {
URLName url = new URLName("smtp", host, port, "", username,password);
transport = new SMTPTransport(session, url);
transport.connect(host, port, username, password);
for (MimeMessage message : messages) {
transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO));
}
return true;
} finally {
if (transport != null) {
transport.close();
}
}
}
}
}

调用方法:

Mail mail=new Mail(host, port, auth, auth_username, auth_password,"1");
String[] test_tos=test_to.split(",");
String alertmsg = mail.sendMessage(test_from, test_tos[0], title, getMessage(request, "a_setting_mailcheck_method_1")+"\n\n\n"+textBody, null);
alertmsg = mail.sendMessage(test_from, test_to, title,getMessage(request, "a_setting_mailcheck_method_2")+"\n\n\n"+textBody, null);
if (alertmsg==null) {
alertmsg=getMessage(request,"a_setting_mailcheck_success_1")+" "+title+" "+getMessage(request, "a_setting_mailcheck_success_2");
}else {
alertmsg=getMessage(request, "a_setting_mailcheck_error")+alertmsg;
}


方法:getMessage()

private MessageResources mr=null;
public String getMessage(HttpServletRequest request,String key,String... args){
if(key==null||key.length()==0){
return null;
}
if(mr==null){
mr=getResources(request);
}
Locale locale=getLocale(request);
String message=null;
if(args!=null&&args.length>0){
message= mr.getMessage(locale,key,args);
}else{
message= mr.getMessage(locale,key);
}
return message;
}
Spring Boot Starter Mail 是 Spring Boot 提供的一个 starters,它简化了发送电子邮件的功能,使得在 Spring 应用程序中集成邮件服务变得更加容易。如果你想通过这个 starter 向多个人群组发送邮件,可以按照以下步骤操作: 1. 首先,在你的项目中添加 `spring-boot-starter-mail` 到依赖中。 2. 配置邮箱服务:通常需要设置邮件服务器的相关信息,如主机名、端口、用户名、密码等。这通常放在 application.properties 或 application.yml 文件中,示例如下: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your_email@example.com spring.mail.password=your_password spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.auth=true ``` 3. 创建 Java 类来处理邮件模板和收件人列表。创建一个包含多个收件人的 List 对象,例如: ```java private List<String> recipients = Arrays.asList("recipient1@example.com", "recipient2@example.com"); ``` 4. 使用 JavaMailTemplate 发送邮件,你可以遍历收件人列表并调用 send() 方法: ```java @Autowired private JavaMailSender javaMailSender; public void sendEmail(String templateName, Map<String, Object> model) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); try { // 设置邮件主题和内容 helper.setSubject(templateName); String htmlContent = "<html><body>" + processTemplate(templateName, model) + "</body></html>"; helper.setText(htmlContent, true); // 如果需要纯文本版本,也可以设置 plainTextBody // 发送给所有收件人 for (String recipient : recipients) { helper.setTo(recipient); javaMailSender.send(message); } } catch (MessagingException e) { log.error("Error sending email", e); } } // 根据模板名称和模型生成 HTML 内容的部分 private String processTemplate(String templateName, Map<String, Object> model) { // ... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值