email - How to send an e-mail from Go -
i'm trying send e-mail in golang , have lot of problems it. i'm new in go maybe cannot find answer on doc.
this want do: 1. e-mail stdin 2. parse e-mail (getting from, to, subject, attachments , on) 3. send e-mail (put again queue in local postfix)
i did 1 , 2 have problem 3th one.
this have now:
package main import ( "fmt" "github.com/jhillyerd/go.enmime" //"github.com/sendgrid/sendgrid-go" "net/smtp" "github.com/jordan-wright/email" "os" "net/mail" "io/ioutil" "bytes" ) func main() { mail_stdin, err := ioutil.readall(os.stdin) if err != nil { return } // convert type io.reader buf := bytes.newbuffer(mail_stdin) msg, err := mail.readmessage(buf) if err != nil { return } mime, err := enmime.parsemimebody(msg) if err != nil { return } # saving attachments _, value := range mime.attachments { fmt.println(value.filename()) err := ioutil.writefile(value.filename(), value.content(), 0664) if err != nil { //panic(err) return } fmt.printf("from: %v\n", msg.header.get("from")) fmt.printf("subject: %v\n", mime.getheader("subject")) fmt.printf("text body: %v chars\n", len(mime.text)) fmt.printf("html body: %v chars\n", len(mime.html)) fmt.printf("inlines: %v\n", len(mime.inlines)) fmt.printf("attachments: %v\n", len(mime.attachments)) fmt.println(mime.attachments) fmt.println(mime.otherparts) fmt.printf("attachments: %v\n", mime.attachments) } i did few tests using: net/smtp, sendgrid-go , jordan-wright/email. want send e-mail (without changing anything) server queue again. of modules needs have auth, want send using sendmail, in same way can bash:
# echo "test" | mail {address}
using net/smtp can easily... assuming have smtp server running can connect without authentication. guess you're trying accomplish it's lot easier through simple gmail ( https://www.digitalocean.com/community/tutorials/how-to-use-google-s-smtp-server )
anyway, here's couple code samples cover either case;
c, err := smtp.dial("mail.example.com:25") if err != nil { log.fatal(err) } defer c.close() // set sender , recipient. c.mail("sender@example.org") c.rcpt("recipient@example.net") // send email body. wc, err := c.data() if err != nil { log.fatal(err) } defer wc.close() buf := bytes.newbufferstring("this email body.") if _, err = buf.writeto(wc); err != nil { log.fatal(err) } alternatively here's go playground example uses simple auth; http://play.golang.org/p/atdcgjgkz3 unless you've got smtp server running on dev box following lot easier.
Comments
Post a Comment