java中发送邮件时如何生产邮件中的表格
时间: 2023-12-14 11:37:29 浏览: 36
在Java中发送邮件时,可以使用HTML格式的内容来创建邮件正文,并在其中添加表格。下面是一个简单的示例代码,用于生成包含表格的HTML邮件正文:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class EmailSender {
public static void main(String[] args) throws MessagingException {
String to = "recipient@example.com";
String subject = "Test Email with Table";
String body = "<html><body>"
+ "<h2>Test Email</h2>"
+ "<table border=\"1\">"
+ "<tr><th>Name</th><th>Age</th></tr>"
+ "<tr><td>John Smith</td><td>35</td></tr>"
+ "<tr><td>Jane Doe</td><td>28</td></tr>"
+ "</table>"
+ "</body></html>";
sendEmail(to, subject, body);
}
public static void sendEmail(String to, String subject, String body) throws MessagingException {
// Set up mail server properties
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a mail session
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
// Create a message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(body, "text/html");
// Send the message
Transport.send(message);
}
}
```
在上面的示例代码中,我们使用了HTML的`<table>`标签来创建一个包含表格的邮件正文。在这个表格中,我们使用了`<th>`标签来创建表头,并使用`<td>`标签来创建单元格。在实际应用中,你可以根据需要调整表格的样式和内容。