Search code examples
gogmail-api

Attaching image to email sent through golang gmail api


I'm trying to attach a picture to an email sent through the gmail golang api, but the image does not attach. I've looked extensively at the documentation, but I have not been able to figure out how to attach an image to an email. Here is the code that I have so far. It only sends the text.

// SendEmailEmbed2 Sends email through gmail
func (config *GmailConfig) SendEmailEmbed2(person int, formattedTemplate string) {

    msg := formattedTemplate

    mmbody := gmail.MessagePartBody{
        Data: encodeWeb64String([]byte(msg)),
    }

    headers := []*gmail.MessagePartHeader{
        &gmail.MessagePartHeader{
            Name:  "From",
            Value: config.FromAddress,
        },
        &gmail.MessagePartHeader{
            Name:  "To",
            Value: config.CSVReference.Elem(person, config.PlugIns[0].ToEmail).String(),
        },
        &gmail.MessagePartHeader{
            Name:  "Subject",
            Value: config.EmailSubject,
        },
        &gmail.MessagePartHeader{
            Name:  "Content-Disposition",
            Value: "./prac2_files/image001.jpg",
        },
    }

    Parts := []*gmail.MessagePart{
        &gmail.MessagePart{
            Filename: "./prac2_files/image001.jpg",
        },
    }

    partgmsg := gmail.MessagePart{
        Body: &mmbody,

        Headers: headers,

        Parts: Parts,

        MimeType: "multipart",
    }

    im, _ := os.Open("./prac2_files/image001.jpg")
    gmsg := gmail.Message{
        Payload: &partgmsg,
        Raw:     encodeWeb64String([]byte(msg)),
    }
    call, err := config.srv.Users.Messages.Send("me", &gmsg).Media(im).Do()

    im.Close()
    if err != nil {
        log.Println("em %v, err %v", gmsg, err)
        // return err
    }
    // return err 

    fmt.Println(person, ":", headers[1].Value, " : ", call.LabelIds)
}

func encodeWeb64String(b []byte) string {

    s := base64.URLEncoding.EncodeToString(b)

    var i = len(s) - 1
    for s[i] == '=' {
        i--
    }

    return s[0 : i+1]
}

Solution

  • Answer:

    You need to attach the file inline in the body of the message.

    Code:

    message := gmail.Message
    
    attachmentBytes := ioutil.ReadFile(fileDir + fileName)
    
    attachmentMimeType: = http.DetectContentType(attachmentBytes)
    
    attachmentData: = base64.StdEncoding.EncodeToString(attachmentBytes)
    
    boundary: = randStr(32, "alphanum")
    
    messageBody: = [] byte("Content-Type: multipart/mixed; boundary=" + boundary + " \n" +
        "MIME-Version: 1.0\n" +
        "to: " + config.CSVReference.Elem(person, config.PlugIns[0].ToEmail).String() + "\n" +
        "from: " + config.FromAddress + "\n" +
        "subject: " + config.EmailSubject + "\n\n" +
    
        "--" + boundary + "\n" +
        "Content-Type: text/plain; charset=" + string('"') + "UTF-8" + string('"') + "\n" +
        "MIME-Version: 1.0\n" +
        "Content-Transfer-Encoding: 7bit\n\n" +
        content + "\n\n" +
        "--" + boundary + "\n" +
    
        "Content-Type: " + "image/jpg" + "; name=" + string('"') + fileName + string('"') + " \n" +
        "MIME-Version: 1.0\n" +
        "Content-Transfer-Encoding: base64\n" +
        "Content-Disposition: attachment; filename=" + string('"') + fileName + string('"') + " \n\n" +
        chunkSplit(attachmentData, 76, "\n") +
        "--" + boundary + "--")
    
    message.Raw = base64.URLEncoding.EncodeToString(messageBody)
    
    _, err := service.Users.Messages.Send("me", &message).Do()
    if err != nil {
        log.Fatalf("Email sending failed: %v", err)
    } else {
        log.Println("Email message sent")
    }