how can i attach mp4 filles to mail with golang (i'm using gomail)

Here is th code:

func sendMail() error{

m := gomail.NewMessage()
m.SetHeader("From", From)
m.SetHeader("To", "[email protected]")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
m.Attach("./video.mp4")
//m.Attach("./Autorizzazione.pdf")

d := gomail.NewDialer(SmtpHost, SmtpPort, From, PswFrom)

// Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil {
    return err
}
return nil}

If attach "Autorizzazione.pdf" it works. Also if I don't attach anthing. But if i try to attach this .mp4 file the output is Error: gomail: could not send email 1: write tcp <my LAN wi-fi ip address>:54988->142.250.147.109:587: wsasend: An existing connection was forcibly closed by the remote host.

This function is called inside an HandleFunc() in my little http server and the return of this function is basically ""printed"" as a return of that api

Can someone help me please?

Upvotes: 0

Views: 287

Answers (1)

suchislife
suchislife

Reputation: 1

Does the following example work for you?

Source: Sending Email And Attachment With GO (Golang) Using SMTP, Gmail, and OAuth2

package gomail

import (
   "errors"
   "fmt"
   "net/smtp"
)

var emailAuth smtp.Auth

func SendEmailSMTP(to []string, data interface{}, template string) (bool, error) {
   emailHost := "smtp.gmail.com"
   emailFrom := "[email protected]"
   emailPassword := "yourEmailPassword"
   emailPort := 587

   emailAuth = smtp.PlainAuth("", emailFrom, emailPassword, emailHost)

   emailBody, err := parseTemplate(template, data)
   if err != nil {
      return false, errors.New("unable to parse email template")
   }

   mime := "MIME-version: 1.0;\nContent-Type: text/plain; charset=\"UTF-8\";\n\n"
   subject := "Subject: " + "Test Email" + "!\n"
   msg := []byte(subject + mime + "\n" + emailBody)
   addr := fmt.Sprintf("%s:%s", emailHost, emailPort)

   if err := smtp.SendMail(addr, emailAuth, emailFrom, to, msg); err != nil {
      return false, err
   }
   return true, nil
}

Upvotes: 0

Related Questions