1

发送或转发电子邮件没有问题。但是,当我尝试将附件作为 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 发送附件,我想知道如何。

4

0 回答 0