如何使用 JavaMail 发送带有附件的 html 电子邮件
how to send a html email with attached file using JavaMail
以下 Java 代码用于将文件附加到 html 电子邮件并发送。我想用这封 html 电子邮件发送附件。如有任何建议,我们将不胜感激。
public void sendEmail(final String userName, final String password, final String host, final String html, final List<String> emails, String subject, String file) throws MessagingException
{
System.out.println("User Name: " + userName);
System.out.println("Password: " + password);
System.out.println("Host: " + host);
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName, password);
}
});
if (!emails.isEmpty())
{
//Compose the message
InternetAddress[] address = new InternetAddress[emails.size()];
for (int i = 0; i < emails.size(); i++)
{
address[i] = new InternetAddress(emails.get(i));
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(html, "text/html; charset=utf-8");
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
} else
{
System.out.println("No Recieptions");
}
}
这只是给我带来的执着。但是我想用这个附件发送 html 电子邮件。
创建一个带有HTML正文和附件的邮件,实际上是创建一个内容为"multipart entity"的邮件,它包含两个部分,其中一个是HTML内容,第二个是附件。
这与您当前的代码不符:
Multipart multipart = new MimeMultipart(); // creating a multipart is OK
// Creating the first body part of the multipart, it's OK
messageBodyPart = new MimeBodyPart();
// ... bla bla
// ok, so this body part is the "attachment file"
messageBodyPart.setDataHandler(new DataHandler(source));
// ... bla bla
multipart.addBodyPart(messageBodyPart); // at this point, the multipart contains your file attachment, but only that!
// at this point, you set your mail's body to be the HTML message
message.setContent(html, "text/html; charset=utf-8");
// and then right after that, you **reset** your mail's content to be your multipart, which does not contain the HTML
message.setContent(multipart);
此时,您的电子邮件内容是一个多部分,只有 1 个部分,即您的附件。
因此,为了达到您的预期结果,您应该采取不同的方式:
- 创建一个多部分(就像你所做的那样)
- 创建一个部分,将您的文件附件作为内容(就像您所做的那样)
- 将第一部分添加到多部分(就像您所做的那样)
- 创建第二个
MimeBodyPart
- 将您的 html 内容添加到第二部分
- 将第二部分添加到您的多部分
- 将您的电子邮件内容设置为多部分(就像您所做的那样)
大致翻译为:
Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource)); //2
attachmentBodyPart.setFileName(file.getName()); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent(htmlMessageAsString , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7
**Send Email using html body and file attachement**
> try {
host = localhost;//use your host or pwd if any
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.auth", "false");
Session session = Session.getInstance(props, null);
MimeMessage mailer = new MimeMessage(session);
// recipient
mailer.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toEmail));
// sender
mailer.setFrom(new InternetAddress(fromEmail));
// cc
if (ccEmail != null) {
for (int i = 0; i < ccEmail.size(); i++) {
String cc = ccEmail.get(i);
mailer.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(cc));
}
}
Transport t = session.getTransport("smtp");
t.connect();
mailer.setSubject(subject);
mailer.setFrom(new InternetAddress(fromEmail));
// attachement
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
BodyPart attachmentBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlbody, "text/html"); // 5
multipart.addBodyPart(messageBodyPart);
// file path
File filename = new File(xmlurl);
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(filename.getName());
multipart.addBodyPart(attachmentBodyPart);
mailer.setContent(multipart);
Transport.send(mailer);
System.out.println("Mail completed");
} catch (SendFailedException e) {//errr
}
}
以下 Java 代码用于将文件附加到 html 电子邮件并发送。我想用这封 html 电子邮件发送附件。如有任何建议,我们将不胜感激。
public void sendEmail(final String userName, final String password, final String host, final String html, final List<String> emails, String subject, String file) throws MessagingException
{
System.out.println("User Name: " + userName);
System.out.println("Password: " + password);
System.out.println("Host: " + host);
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName, password);
}
});
if (!emails.isEmpty())
{
//Compose the message
InternetAddress[] address = new InternetAddress[emails.size()];
for (int i = 0; i < emails.size(); i++)
{
address[i] = new InternetAddress(emails.get(i));
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(html, "text/html; charset=utf-8");
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
} else
{
System.out.println("No Recieptions");
}
}
这只是给我带来的执着。但是我想用这个附件发送 html 电子邮件。
创建一个带有HTML正文和附件的邮件,实际上是创建一个内容为"multipart entity"的邮件,它包含两个部分,其中一个是HTML内容,第二个是附件。
这与您当前的代码不符:
Multipart multipart = new MimeMultipart(); // creating a multipart is OK
// Creating the first body part of the multipart, it's OK
messageBodyPart = new MimeBodyPart();
// ... bla bla
// ok, so this body part is the "attachment file"
messageBodyPart.setDataHandler(new DataHandler(source));
// ... bla bla
multipart.addBodyPart(messageBodyPart); // at this point, the multipart contains your file attachment, but only that!
// at this point, you set your mail's body to be the HTML message
message.setContent(html, "text/html; charset=utf-8");
// and then right after that, you **reset** your mail's content to be your multipart, which does not contain the HTML
message.setContent(multipart);
此时,您的电子邮件内容是一个多部分,只有 1 个部分,即您的附件。
因此,为了达到您的预期结果,您应该采取不同的方式:
- 创建一个多部分(就像你所做的那样)
- 创建一个部分,将您的文件附件作为内容(就像您所做的那样)
- 将第一部分添加到多部分(就像您所做的那样)
- 创建第二个
MimeBodyPart
- 将您的 html 内容添加到第二部分
- 将第二部分添加到您的多部分
- 将您的电子邮件内容设置为多部分(就像您所做的那样)
大致翻译为:
Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource)); //2
attachmentBodyPart.setFileName(file.getName()); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent(htmlMessageAsString , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7
**Send Email using html body and file attachement**
> try {
host = localhost;//use your host or pwd if any
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.auth", "false");
Session session = Session.getInstance(props, null);
MimeMessage mailer = new MimeMessage(session);
// recipient
mailer.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toEmail));
// sender
mailer.setFrom(new InternetAddress(fromEmail));
// cc
if (ccEmail != null) {
for (int i = 0; i < ccEmail.size(); i++) {
String cc = ccEmail.get(i);
mailer.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(cc));
}
}
Transport t = session.getTransport("smtp");
t.connect();
mailer.setSubject(subject);
mailer.setFrom(new InternetAddress(fromEmail));
// attachement
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
BodyPart attachmentBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlbody, "text/html"); // 5
multipart.addBodyPart(messageBodyPart);
// file path
File filename = new File(xmlurl);
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(filename.getName());
multipart.addBodyPart(attachmentBodyPart);
mailer.setContent(multipart);
Transport.send(mailer);
System.out.println("Mail completed");
} catch (SendFailedException e) {//errr
}
}