如何通过谷歌应用引擎发送带有CSV文件附件的Gmail邮件

时间:2012-04-02 09:53:50

标签: java google-app-engine java-ee

我正在尝试通过谷歌应用引擎发送带有csv附件的电子邮件收件人没有收到邮件。当我在Google App Engine中检查日志时,也没有报告任何错误。怎么可能出错?有人可以告诉我是否可以使用Goog应用引擎通过邮件发送csv文件作为附件?如果是的话,你能告诉我怎么做吗?

      Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);

try {
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("xxx@gmail.com"," Admin"));
         msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailto, "Mr. User"));
    msg.setSubject("Expence Tracker with Attachment");

    String htmlBody=msgbody;   

    byte[] attachmentData= attach.getBytes(); 
         Multipart mp = new MimeMultipart();

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlBody, "text/html");
    mp.addBodyPart(htmlPart);

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setFileName("myfile.csv");
    attachment.setContent(attachmentData, "text/comma-separated-values");
    mp.addBodyPart(attachment);

    msg.setContent(mp);

    //resp.getWriter().println("Mail  Details :To- "+emailto);

} catch (AddressException e) {

    resp.getWriter().println("Mail  Details :Error "+e);
} catch (MessagingException e) {
    resp.getWriter().println("Mail  Details :Error "+e);
}

1 个答案:

答案 0 :(得分:0)

这是发送CSV附件的示例。 CSV位于blobstore中。 它是在Python中使用GAE Mail和blobstore API。将其翻译成Java并不困难。

    blob_key = files.blobstore.get_blob_key(file_name)
    blob_info = blobstore.BlobInfo.get(blob_key)        
    blob_reader = blobstore.BlobReader(blob_key)                        
    message = mail.EmailMessage(sender = 'noreply@example.com, 
                                subject = 'CSV attached')        
    message.body = 'Download attached CSV'                       # only a text body
    message.attachments = [blob_info.filename,blob_reader.read()]
    message.send()