Sunday, November 7, 2010

How to Send Email with Attachments Using Google App Engine

The cool thing about Google App Engine is that you can send e-mails from there for free (well, up to 2000 per day). You can even send attachments with it!

How do you do that? Here is a code snippet. Note that two cases are dealt here, one when there are attachments (so a multi part message is created) and the simplest case where there no attachments:


private static String SendEmail(String user, String to,
    String cc, String subject, String body, String filename,
    String mimeType, byte[] rawData)
{
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(user));
        message.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(to));
        if (cc != null && !cc.trim().isEmpty()) {
              message.addRecipient(Message.RecipientType.CC,
                             new InternetAddress(cc));                    
        }
        message.setSubject(subject, "UTF-8");

        if (rawData != null && filename != null &&
           !filename.isEmpty()) {
             if (mimeType == null || mimeType.isEmpty()) {
                 mimeType = GetMimeType(filename);
             }

             Multipart mp = new MimeMultipart();
             MimeBodyPart htmlPart = new MimeBodyPart();

             htmlPart.setContent(body, "text/html");
             mp.addBodyPart(htmlPart);
             ByteArrayDataSource dataSource = new
                 ByteArrayDataSource(rawData, mimeType);
     
             MimeBodyPart attachment = new MimeBodyPart();
             attachment.setFileName(filename);
             attachment.setDataHandler(
                 new DataHandler(dataSource));                                  
             mp.addBodyPart(attachment);

             message.setContent(mp);
         }
         else {
             message.setText(body, "UTF-8");
         }

         Transport.send(message);
     } catch (Exception e) {
          return "Error: " + e.getMessage();
     } 
     return "ok";
}

1 comment:

  1. Hi Vassilli,

    Thanks for sharing good stuff with us. Really it saved good enough time. One compiler issue come at line GetMimeType method. So I just changed
    filename = GetMimeType(filename);
    to
    mimeType = new MimetypesFileTypeMap().getContentType(filename);

    Again thanks.

    Regards,

    Binod Suman

    ReplyDelete