java发送邮件html表格
时间: 2024-06-23 17:03:00 浏览: 191
Java发送html邮件
在Java中,你可以使用JavaMail API来发送包含HTML格式(包括表格)的电子邮件。以下是一个简单的示例,展示了如何创建一个带有HTML表格的邮件:
```java
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender {
public static void main(String[] args) {
// 设置邮件属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
// 获取Session对象并进行验证
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
try {
// 创建MimeMessage对象
Message message = new MimeMessage(session);
// 设置发件人和收件人
message.setFrom(new InternetAddress("your-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email@example.com"));
// 设置邮件主题和内容
message.setSubject("HTML Table Email");
String htmlContent = "<html><body>"
+ "<h1>Hello, World!</h1>"
+ "<table border=\"1\"><tr><th>Column 1</th><th>Column 2</th></tr>"
+ "<tr><td>Row 1, Cell 1</td><td>Row 1, Cell 2</td></tr>"
+ "</table>"
+ "</body></html>";
message.setContent(htmlContent, "text/html; charset=UTF-8");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
阅读全文