我有用于发送带附件的电子邮件的java代码,如下所示。
String myEmailId = "xx@yahoo.co.in";
String myPassword = "@xx";
String senderId = "yy@gmail.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.mail.yahoo.com");
email.addTo(senderId);
email.setFrom(myEmailId);
email.setSubject("The picture");
email.setMsg("<font face='verdana' size='3'>Here is the picture you wanted "
+ "<table>"
+ "<tr><th>id</th><th>Name</th></tr>"
+ "<tr><th>1</th><th>Name 1</th></tr>"
+ "<tr><th>2</th><th>Name 2</th></tr>"
+ "<tr><th>3</th><th>Name 3</th></tr>"
+ "<tr><th>4</th><th>Name 4</th></tr>"
+ "</table>"
+ "</font>");
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test_small.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
// send the email
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
一切正常,除了HTML代码显示原样。
在电子邮件中,我得到的是
<font face='verdana' size='3'>Here is the picture you wanted <table><tr><th>id</th><th>Name</th></tr><tr><th>1</th><th>Name 1</th></tr><tr><th>2</th><th>Name 2</th></tr><tr><th>3</th><th>Name 3</th></tr><tr><th>4</th><th>Name 4</th></tr></table></font>
是否有任何参数,我将收到的电子邮件将包含正确的HTML格式数据。
注意:
实际上我正在使用Email email = new SimpleEmail();
并在HTML部分工作正常的情况下做上面的事情。但是当我不得不切换到附件时,我不得不使用MultiPartEmail email = new MultiPartEmail();
。
答案 0 :(得分:1)
我得到了答案。
刚刚将MultiPartEmail email = new MultiPartEmail();
更改为MultiPartEmail email = new HtmlEmail();
答案 1 :(得分:1)
你不能使用 - email.setMsg( 但将正文消息设置为: email.addPart(“
答案 2 :(得分:1)
我想在这里提供我的答案,以便将来我(和其他人)可以看到完整的代码。无论出于何种原因,可能只是我,我发现这些答案不完整,或者说它们对我不起作用。和OP一样,我试图发送带有PDF附件的基于HTML的电子邮件。以下是我最后使用commons-email 1.4的内容。任何意见将不胜感激。
进口:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.EmailAttachment;
构建您的电子邮件对象(显然这里的实际细节应该是您的)
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.yourhosthere.com");
email.setSmtpPort(25);
// authentication not always needed depending on your environment
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setTo("to@yourhosthere.com");
email.setFrom("from@yourhosthere.com");
现在您的留言详情。请注意,我的HTML包含HTML和BODY标记。
email.setSubject("Your subject here");
email.addPart("<div>Your html here</div>", "text/html; charset=UTF-8");
现在附件
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(filepath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
现在发送电子邮件
email.send();