Send email with go (SMTP)

8,719 views
Skip to first unread message

kar

unread,
May 31, 2011, 10:48:19 PM5/31/11
to golang-nuts
Can somebody provide an example on how to send email with smtp
package.
Thanks.

smallfish

unread,
May 31, 2011, 10:50:35 PM5/31/11
to kar, golang-nuts

Andrew Gerrand

unread,
May 31, 2011, 11:35:19 PM5/31/11
to kar, golang-nuts
On 1 June 2011 12:48, kar <akma...@gmail.com> wrote:
> Can somebody provide an example on how to send email with smtp
> package.

Here you go:

http://code.google.com/p/go-wiki/wiki/SendingMail

Andrew

kar

unread,
May 31, 2011, 11:56:37 PM5/31/11
to golang-nuts
Thanks Andrew, that should get me started.

On Jun 1, 11:35 am, Andrew Gerrand <a...@golang.org> wrote:

Evan Shaw

unread,
Jun 1, 2011, 1:22:27 AM6/1/11
to Andrew Gerrand, kar, golang-nuts

This example "works", but in the real world you almost always need to
authenticate and before you do that you usually need to start TLS.

It's probably also better to have an example that uses smtp.SendMail
since that covers the vast majority of use cases. The equivalent
(including authentication) would be:

package main

import (
"log"
"smtp"
)

func main() {
auth := smt.PlainAuth("", "us...@example.com", "password",
"mail.example.com")
err := smtp.SendMail("mail.example.com:25", auth,
"sen...@example.org", []string{"reci...@example.net"}, []byte("This
is the email body."))
if err != nil {
log.Fatal(err)
}
}

- Evan

Russ Cox

unread,
Jun 1, 2011, 10:01:54 AM6/1/11
to Evan Shaw, Andrew Gerrand, kar, golang-nuts
> This example "works", but in the real world you almost always need to
> authenticate and before you do that you usually need to start TLS.
>
> It's probably also better to have an example ...

You have write access to the wiki. :-)

gocss

unread,
Jul 7, 2011, 6:42:21 PM7/7/11
to golang-nuts
I'm trying email from within GO working on a server
which under Thunderbird requires:
connection security: SSL/TLS
authentication method Normal password
)

can I use the smt.PlainAuth() and if so how do I indicate 'SSL/TLS'

On Jun 1, 1:22 am, Evan Shaw <eds...@gmail.com> wrote:
> On Wed, Jun 1, 2011 at 3:35 PM, Andrew Gerrand <a...@golang.org> wrote:
> > On 1 June 2011 12:48, kar <akmal...@gmail.com> wrote:
> >> Can somebody provide an example on how to send email with smtp
> >> package.
>
> > Here you go:
>
> >http://code.google.com/p/go-wiki/wiki/SendingMail
>
> > Andrew
>
> This example "works", but in the real world you almost always need to
> authenticate and before you do that you usually need to start TLS.
>
> It's probably also better to have an example that uses smtp.SendMail
> since that covers the vast majority of use cases. The equivalent
> (including authentication) would be:
>
> package main
>
> import (
>     "log"
>     "smtp"
> )
>
> func main() {
>     auth := smt.PlainAuth("", "u...@example.com", "password",
> "mail.example.com")
>     err := smtp.SendMail("mail.example.com:25", auth,
> "sen...@example.org", []string{"recipi...@example.net"}, []byte("This

Evan Shaw

unread,
Jul 7, 2011, 6:49:25 PM7/7/11
to gocss, golang-nuts
On Fri, Jul 8, 2011 at 10:42 AM, gocss <g...@curtissystemssoftware.com> wrote:
> I'm trying email from within GO working on a server
> which under Thunderbird requires:
> connection security: SSL/TLS
> authentication method Normal password
> )
>
> can I use the smt.PlainAuth() and if so how do I indicate 'SSL/TLS'

"Normal password" sounds like PlainAuth would work. If you use
smtp.SendMail, it will switch to TLS automatically once it detects
that the server supports it.

It's possible, though unlikely, that your server requires TLS from the
very beginning. In that case you'd have to create your own TLS
connection, then use smtp.NewClient, and run through the SendMail
steps manually.

- Evan

T.J. Yang

unread,
Dec 5, 2013, 2:21:13 PM12/5/13
to golan...@googlegroups.com, gocss
I am able to use following sample to send out email but with empty Subject line.

https://code.google.com/p/go-wiki/wiki/SendingMail

I looked at doc at http://godoc.org/net/smtp

How can I modify the sample code to allow message in "Subject" field ?


tj

Chuck Ha

unread,
Dec 5, 2013, 2:59:49 PM12/5/13
to golan...@googlegroups.com, gocss
You want something like this

body := []byte(fmt.Sprintf("Subject: %s\r\n\r\n%s", subject, body))

Alexandre Fiori

unread,
Dec 5, 2013, 3:00:48 PM12/5/13
to golan...@googlegroups.com, gocss


On Thursday, December 5, 2013 2:21:13 PM UTC-5, T.J. Yang wrote:

T.J. Yang

unread,
Dec 5, 2013, 4:11:08 PM12/5/13
to golan...@googlegroups.com, gocss


On Thursday, December 5, 2013 2:00:48 PM UTC-6, Alexandre Fiori wrote:


This is my current shell scrip that calling up mailx command
# -r = From sender's email address
# -s = Email subject
# last argument= recipient's email address
echo "Body by mailx" | mailx -r "b...@example.com" -s "testing mailx" "j...@example.com"
 

I just want to know how can I add a test string like "Saying hello" in the Email subject.
something as easy as following


   // Set the sender and recipient.
        c
.Mail("sen...@example.org")
        c
.Rcpt("reci...@example.net")
        c. Subject("Saying hello")



tj 

Rick Tait

unread,
Dec 5, 2013, 4:11:40 PM12/5/13
to golan...@googlegroups.com
@TJ you can do something like this:

package main

import (
  "crypto/tls"
  "fmt"
  "log"
  "net"
  "net/mail"
  "net/smtp"
)

func main() {
  // the basics
  from := mail.Address{"senders name", "user...@sender.com"}
  to := mail.Address{"recipients name", "user...@recipient.com"}
  body := "this is the body line1.\nthis is the body line2.\nthis is the body line3.\n"
  subject := "this is the subject line"

  // setup the remote smtpserver & auth info
  smtpserver := "remote.mailserver.com:25"
  auth := smtp.PlainAuth("", "user...@sender.com", "senders-password", "remote.mailserver.com")

  // setup a map for the headers
  header := make(map[string]string)
  header["From"] = from.String()
  header["To"] = to.String()
  header["Subject"] = subject

  // setup the message
  message := ""
  for k, v := range header {
    message += fmt.Sprintf("%s: %s\r\n", k, v)
  }
  message += "\r\n" + body

  // create the smtp connection
  c, err := smtp.Dial(smtpserver)
  if err != nil {
    log.Panic(err)
  }

  // set some TLS options, so we can make sure a non-verified cert won't stop us sending
  host, _, _ := net.SplitHostPort(smtpserver)
  tlc := &tls.Config{
    InsecureSkipVerify: true,
    ServerName:         host,
  }
  if err = c.StartTLS(tlc); err != nil {
    log.Panic(err)
  }

  // auth stuff
  if err = c.Auth(auth); err != nil {
    log.Panic(err)
  }

  // To && From
  if err = c.Mail(from.Address); err != nil {
    log.Panic(err)
  }
  if err = c.Rcpt(to.Address); err != nil {
    log.Panic(err)
  }

  // Data
  w, err := c.Data()
  if err != nil {
    log.Panic(err)
  }
  _, err = w.Write([]byte(message))
  if err != nil {
    log.Panic(err)
  }
  err = w.Close()
  if err != nil {
    log.Panic(err)
  }
  c.Quit()
}

note that i am explicitly setting the tls.Config option to allow self-signed/non-verified certs, but you may not need this.

RMT.

Bill Hogsett

unread,
Dec 5, 2013, 4:32:32 PM12/5/13
to golan...@googlegroups.com
Rick Tait's code worked perfectly for me using gmail as the smtp server.


Matt Silverlock

unread,
Dec 5, 2013, 5:09:14 PM12/5/13
to golan...@googlegroups.com
Putting your Gmail password in the source (and plaintext) seems awfully risky.

Use something like Mandrill (https://mandrillapp.com/api/docs/messages.html) + the gochimp library (https://github.com/mattbaird/gochimp) instead.

You can then use templates on your side (e.g. template/text) or theirs (using merge variables) so you don't have to worry about format strings.

I've been using this for a small project and it's been pretty robust. Easy to track bounces as well, which can be useful.

Rick Tait

unread,
Dec 5, 2013, 6:22:09 PM12/5/13
to golan...@googlegroups.com
agreed. i would never normally put any kind of credential information in src, and did so only for the purposes of explanatory code! more of a json config file man, myself.

RMT

T.J. Yang

unread,
Dec 5, 2013, 6:52:58 PM12/5/13
to golan...@googlegroups.com
Hi Rick and all

Following is the version I used to send out email. 

Thanks for the quick response and  helping  me learn golang.

Someone with wiki edit right, please add Rick's two examples into go wik. 
 

// an example to send out email without authentication with mail server.
package main
import (
  "fmt"
  "log"
  "net/mail"
  "net/smtp"
)

func main() {
  // the basics
  from := mail.Address{"Joe X", "j...@example.com"}
  to   := mail.Address{"Bob Y", "b...@example.com"}
  body := "this is the body line1.\nthis is the body line2.\nthis is the body line3.\n"
  subject := "this is the subject line"

  // setup the remote smtpserver
  smtpserver := "remotesmtp.example.net:25"

  // setup a map for the headers
  header := make(map[string]string)
  header["From"] = from.String()
  header["To"] = to.String()
  header["Subject"] = subject

  // setup the message
  message := ""
  for k, v := range header {
    message += fmt.Sprintf("%s: %s\r\n", k, v)
  }
  message += "\r\n" + body

  // create the smtp connection
  c, err := smtp.Dial(smtpserver)
  if err != nil {
    log.Panic(err)
  }

  // To && From
  if err = c.Mail(from.Address); err != nil {
    log.Panic(err)
  }
  if err = c.Rcpt(to.Address); err != nil {
    log.Panic(err)
  }

  // Data
  w, err := c.Data()
  if err != nil {
    log.Panic(err)
  }
  _, err = w.Write([]byte(message))
  if err != nil {
    log.Panic(err)
  }
  err = w.Close()
  if err != nil {
    log.Panic(err)
  }
  c.Quit()
}


T.J. Yang

unread,
Dec 5, 2013, 10:13:25 PM12/5/13
to golan...@googlegroups.com, gocss


On Thursday, December 5, 2013 1:59:49 PM UTC-6, Chuck Ha wrote:
You want something like this

body := []byte(fmt.Sprintf("Subject: %s\r\n\r\n%s", subject, body))

Hi Chuck,

Thanks for the pointer. following is a working example from your suggestion.


// Mail message = header + body
// Example message is between ---- and ----
// ----
// From: John Doe <jd...@machine.example>
// To: Mary Smith <ma...@example.net>
// Subject: Saying Hello
// Date: Fri, 21 Nov 1997 09:55:06 -0600
// Message-ID: <12...@local.machine.example>
//
// This is a message just to say hello.
// So, "Hello".
// ----

package main

import (
        "bytes"
        "log"
        "fmt"
        "net/smtp"
)

func main() {
        // Connect to the remote SMTP server.
        c, err := smtp.Dial("remotesmtp.example.com:25")
        if err != nil {
                log.Fatal(err)
        }
        // Set the sender in header.
        c.Mail("ma...@example.net")
        // Set the recipient in header
        c.Rcpt("ma...@example.net")

// Connecting to mail server ?.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
        defer wc.Close()
subject := "Saying Hello"
body := "So, Hello"
message := bytes.NewBufferString(fmt.Sprintf("Subject: %s\r\n\r\n%s", subject, body))
// Now push out the complete mail message
if _, err = message.WriteTo(wc); err != nil {
log.Fatal(err)
}
}

Stéphane phenetas

unread,
Aug 27, 2015, 10:11:10 PM8/27/15
to golang-nuts
Hi, I wanted to ask a question about sending a mail with Golang, I think the question can fit here as this is a general thread about SMTP in Go.

My question is : How can I set the "Object" field when i send a mail ?

thank you.

James Bardin

unread,
Aug 28, 2015, 9:20:26 AM8/28/15
to golang-nuts
Please don't dig up old threads to ask new questions.


On Thursday, August 27, 2015 at 10:11:10 PM UTC-4, Stéphane phenetas wrote:
Hi, I wanted to ask a question about sending a mail with Golang, I think the question can fit here as this is a general thread about SMTP in Go.

My question is : How can I set the "Object" field when i send a mail ?


What do you mean by "Object" field?
If you mean a header named "Object", you write new headers just like any others as part of the RFC 822-style email message. 


Stéphane phenetas

unread,
Aug 28, 2015, 4:48:35 PM8/28/15
to golang-nuts
Hi, Sorry it was a bad translation. I meant the "Subject" field. I can set up the "To:", the "From:" and the message itself, but I can not set up a Subject description.
How can I do this ?

Matt Harden

unread,
Aug 28, 2015, 5:03:48 PM8/28/15
to Stéphane phenetas, golang-nuts
Subject is just another header field, like To and From. See the example http://godoc.org/net/smtp#example-SendMail.

On Fri, Aug 28, 2015 at 3:48 PM Stéphane phenetas <phen...@gmail.com> wrote:
Hi, Sorry it was a bad translation. I meant the "Subject" field. I can set up the "To:", the "From:" and the message itself, but I can not set up a Subject description.
How can I do this ?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages