作者:萌萌虾 | 来源:互联网 | 2024-11-19 12:12
在使用JavaMail库发送带有抄送功能的邮件时,有时会遇到抄送人无法收到邮件的情况。这通常是由于配置不当或邮件服务器限制引起的。本文将详细介绍如何正确配置JavaMail,确保抄送功能正常运行。
首先,确保你的项目中包含了必要的JavaMail依赖。在Maven项目中,需要在pom.xml文件中添加如下依赖:
com.sun.mail
javax.mail
1.5.6
com.sun.mail
smtp
1.5.2
接下来,我们来看一个简单的JavaMail服务类,该类用于发送包含抄送功能的邮件:
package com.ssm.boot.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class MailService {
private static final Logger logger = LoggerFactory.getLogger(MailService.class);
private static final String DEFAULT_SENDER_NAME = "your-email@example.com";
private static final String DEFAULT_SENDER_PASS = "your-password";
private static final String DEFAULT_SMTP_HOST = "smtp.example.com";
private String smtpHost;
private String sendUserName;
private String sendUserPass;
private MimeMessage mimeMsg;
private Session session;
private Properties props;
private Multipart multipart;
private List attachments = new LinkedList<>();
public MailService(String smtpHost, String sendUserName, String sendUserPass, String to, String cc, String subject, String body, List attachments) {
this.smtpHost = smtpHost;
this.sendUserName = sendUserName;
this.sendUserPass = sendUserPass;
init();
setFrom(sendUserName);
setTo(to);
setCc(cc);
setSubject(subject);
setBody(body);
if (attachments != null) {
for (String attachment : attachments) {
addAttachment(attachment);
}
}
}
private void init() {
if (props == null) {
props = System.getProperties();
}
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(props, null);
session.setDebug(true);
mimeMsg = new MimeMessage(session);
multipart = new MimeMultipart();
}
public static MailService create(String smtpHost, String sendUserName, String sendUserPass, String to, String cc, String subject, String body, List attachments) {
return new MailService(smtpHost, sendUserName, sendUserPass, to, cc, subject, body, attachments);
}
public static MailService createDefault(String to, String cc, String subject, String body, List attachments) {
return new MailService(DEFAULT_SMTP_HOST, DEFAULT_SENDER_NAME, DEFAULT_SENDER_PASS, to, cc, subject, body, attachments);
}
private boolean setSubject(String subject) {
try {
mimeMsg.setSubject(subject);
} catch (MessagingException e) {
logger.error("Failed to set subject: ", e);
return false;
}
return true;
}
private boolean setBody(String body) {
try {
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(body, "text/html;charset=UTF-8");
multipart.addBodyPart(bodyPart);
} catch (MessagingException e) {
logger.error("Failed to set body: ", e);
return false;
}
return true;
}
private boolean addAttachment(String filename) {
try {
if (filename != null && !filename.isEmpty()) {
BodyPart bodyPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(filename);
bodyPart.setDataHandler(new DataHandler(fileDataSource));
bodyPart.setFileName(MimeUtility.encodeText(fileDataSource.getName(), "utf-8", null));
multipart.addBodyPart(bodyPart);
attachments.add(filename);
}
} catch (Exception e) {
logger.error("Failed to add attachment: ", e);
return false;
}
return true;
}
private boolean setFrom(String from) {
try {
mimeMsg.setFrom(new InternetAddress(from));
} catch (MessagingException e) {
logger.error("Failed to set from address: ", e);
return false;
}
return true;
}
private boolean setTo(String to) {
if (to == null) return false;
try {
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
} catch (MessagingException e) {
logger.error("Failed to set to address: ", e);
return false;
}
return true;
}
private boolean setCc(String cc) {
if (cc == null) return false;
try {
mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
} catch (MessagingException e) {
logger.error("Failed to set cc address: ", e);
return false;
}
return true;
}
public boolean send() {
try {
mimeMsg.setContent(multipart);
mimeMsg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, sendUserName, sendUserPass);
transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
transport.close();
logger.info("Email sent successfully.");
return true;
} catch (Exception e) {
logger.error("Failed to send email: ", e);
return false;
}
}
public static void main(String[] args) {
String userName = "your-email@example.com";
String password = "your-password";
String smtpHost = "smtp.example.com";
String to = "recipient@example.com";
String cc = "cc-recipient1@example.com,cc-recipient2@example.com";
String subject = "Test Email Subject";
String body = "This is the body of the test email.";
List attachments = Arrays.asList("path/to/file1.pdf", "path/to/file2.docx");
MailService email = MailService.create(smtpHost, userName, password, to, cc, subject, body, attachments);
email.send();
}
}