yonojoy yonojoy - 11 months ago 74
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>");
.setSubject("Subject goes here")
.setText("Hello World!")

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

Answer Source

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.setSubject("Sending with SendGrid is Fun");
    email.setHtml("and easy to do anywhere, even with Java");

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


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;