发送或转发电子邮件没问题。但是,当我尝试发送和附件为mime multipart时,附件不会被发送。我已经搜索了现有的帖子并尝试了多种方法来修复。低级MailService工作,但JavaMail不工作。我将发布两个代码片段,希望有人会得到答案。
发件人是应用管理员,但已在代码段中进行了更改。
什么有效,这是低级API调用:
String htmlBody = "Data dump from " + host + ". See attached.";
Properties props = new Properties();
Session session = Session.getInstance(props, null); // not used
MailService service = MailServiceFactory.getMailService();
MailService.Message msg = new MailService.Message();
msg.setSender("myUser@gmail.com");
msg.setTo("anotherUser@gmail.com");
msg.setSubject("Committee Participation Report");
msg.setHtmlBody(htmlBody);
MailService.Attachment attachment = new MailService.Attachment("data-dump.cvs",
report.getBytes());
msg.setAttachments(attachment);
service.send(msg);
什么不起作用,JavaMail API调用:
Properties props = new Properties();
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom("admins");
msg.addRecipient(Message.RecipientType.TO, "aUser@gmail.com");
msg.setSubject("a subject");
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html");
mp.addBodyPart(htmlPart);
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(new ByteArrayDataSource(report.getBytes(), "text/comma-separated-values")));
attachment.setFileName("cvsfile.csv");
mp.addBodyPart(attachment);
msg.setContent(mp);
Transport.send(msg);
对于带或不带附件的电子邮件使用相同的API会很好,所以如果有人能够让JavaMail API发送附件,我想知道如何。