yonojoy yonojoy - 2 months ago 20
Java Question

How to add an attachment to an email sent from Google App Engine via SendGrid (in Java)?

I followed Google's information to send an email from App Engine via SendGrid. This is working fine using the Java library for SendGrid and the provided example code:

import packageName.Sendgrid;

Sendgrid mail = new Sendgrid("<sendgrid_username>","<sendgrid_password>");
mail.setTo("foo@bar.com")
.setFrom("me@bar.com")
.setSubject("Subject goes here")
.setText("Hello World!")
mail.send();


But now I need to attach an file. How can this be done? I cannot find an
addAttachment
-function or something like that in the
sendgrid-google-java
library
.

Answer

I just use the SendGrid Java API on appengine, not a specific google one. Here's an example:

import com.sendgrid.*;

public class SendGridExample {
  public static void main(String[] args) {
    SendGrid sendgrid = new SendGrid("SENDGRID_APIKEY");

    SendGrid.Email email = new SendGrid.Email();

    email.addTo("test@sendgrid.com");
    email.setFrom("you@youremail.com");
    email.setSubject("Sending with SendGrid is Fun");
    email.setHtml("and easy to do anywhere, even with Java");

    SendGrid.Response response = sendgrid.send(email);
  }
}

https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/java.html

You can add attachments to this email object using either one of these 3 functions:

    public Email addAttachment(String name, File file) throws IOException, FileNotFoundException {
        return this.addAttachment(name, new FileInputStream(file));
    }

    public Email addAttachment(String name, String file) throws IOException {
        return this.addAttachment(name, new ByteArrayInputStream(file.getBytes()));
    }

    public Email addAttachment(String name, InputStream file) throws IOException {
        this.attachments.put(name, file);
        return this;
    }