返回
Java 发邮件:带附件且正文 html 格式
后端
2023-11-17 20:46:22
在 Java 中发送电子邮件,我们需要使用 JavaMail API。JavaMail API 是一个 Java 库,它提供了一个统一的 API 来发送电子邮件。它支持多种电子邮件协议,包括 SMTP、POP3 和 IMAP。
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// 设置邮件服务器的属性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 创建一个新的邮件会话
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
// 创建一封新的邮件
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@gmail.com"));
message.setSubject("This is a test email with attachment");
// 设置邮件正文
String htmlContent = "<h1>This is the HTML content of the email</h1>";
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html");
// 设置附件
MimeBodyPart attachmentPart = new MimeBodyPart();
File file = new File("attachment.txt");
attachmentPart.attachFile(file);
// 将正文和附件组合成一个邮件
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(htmlPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully!");
}
}
使用 JavaMail API 发送电子邮件非常简单。只需要几行代码,就可以发送一封带附件和 HTML 格式正文的电子邮件。
希望本文对您有所帮助。如果您有任何问题,请随时留言。