blob: d453474bf66f12709bbf2501daa650f4d3de104b [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001# Sending Mail
2
Alexandre Cesaro4980e252015-09-08 14:08:24 +02003See also:
4* [net/smtp](http://golang.org/pkg/net/smtp/)
5* [Email packages](https://github.com/golang/go/wiki/Projects#email)
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11006
7Streaming the body:
8
bom-d-vandaa324d2015-01-03 22:21:18 -08009```go
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110010package main
11
12import (
Dave Day0d6986a2014-12-10 15:02:18 +110013 "bytes"
14 "log"
15 "net/smtp"
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110016)
17
18func main() {
Dave Day0d6986a2014-12-10 15:02:18 +110019 // Connect to the remote SMTP server.
20 c, err := smtp.Dial("mail.example.com:25")
21 if err != nil {
22 log.Fatal(err)
23 }
miffedmap51a2e412015-02-26 20:32:41 +020024 defer c.Close()
Dave Day0d6986a2014-12-10 15:02:18 +110025 // Set the sender and recipient.
26 c.Mail("sender@example.org")
27 c.Rcpt("recipient@example.net")
28 // Send the email body.
29 wc, err := c.Data()
30 if err != nil {
31 log.Fatal(err)
32 }
33 defer wc.Close()
34 buf := bytes.NewBufferString("This is the email body.")
35 if _, err = buf.WriteTo(wc); err != nil {
36 log.Fatal(err)
37 }
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110038}
39```
40
41Authenticated SMTP:
42
bom-d-vandaa324d2015-01-03 22:21:18 -080043```go
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110044package main
45
46import (
47 "log"
48 "net/smtp"
49)
50
51func main() {
52 // Set up authentication information.
53 auth := smtp.PlainAuth(
54 "",
55 "user@example.com",
56 "password",
57 "mail.example.com",
58 )
59 // Connect to the server, authenticate, set the sender and recipient,
60 // and send the email all in one step.
61 err := smtp.SendMail(
62 "mail.example.com:25",
63 auth,
64 "sender@example.org",
65 []string{"recipient@example.net"},
66 []byte("This is the email body."),
67 )
68 if err != nil {
69 log.Fatal(err)
70 }
71}
72```