可以使用JavaMail API来实现。JavaMail API是Java平台上用于发送和接收电子邮件的标准API。
首先,需要导入JavaMail API的相关库。可以在Maven或Gradle中添加以下依赖项:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
接下来,可以使用以下代码示例来发送HTML邮件:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendHtmlEmail {
public static void main(String[] args) {
// 邮件配置
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com"); // 设置SMTP服务器地址
properties.put("mail.smtp.port", "587"); // 设置SMTP服务器端口
properties.put("mail.smtp.auth", "true"); // 启用SMTP身份验证
properties.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密
// 创建会话
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@example.com", "your-password"); // 设置发件人邮箱和密码
}
});
try {
// 创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@example.com")); // 设置发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com")); // 设置收件人
message.setSubject("HTML邮件"); // 设置邮件主题
// 创建邮件内容
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<h1>Hello, World!</h1>", "text/html"); // 设置HTML内容
// 将邮件内容添加到Multipart对象中
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// 设置邮件内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
上述代码中,需要替换以下内容:
smtp.example.com
:SMTP服务器地址587
:SMTP服务器端口your-email@example.com
:发件人邮箱your-password
:发件人邮箱密码recipient@example.com
:收件人邮箱这样,通过Java就可以将HTML内容发送到任何电子邮件地址。
领取专属 10元无门槛券
手把手带您无忧上云