Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Sending Mail |
| 2 | |
| 3 | See also: http://golang.org/pkg/net/smtp/ |
| 4 | |
| 5 | Streaming the body: |
| 6 | |
| 7 | ``` |
| 8 | package main |
| 9 | |
| 10 | import ( |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 11 | "bytes" |
| 12 | "log" |
| 13 | "net/smtp" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 14 | ) |
| 15 | |
| 16 | func main() { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 17 | // Connect to the remote SMTP server. |
| 18 | c, err := smtp.Dial("mail.example.com:25") |
| 19 | if err != nil { |
| 20 | log.Fatal(err) |
| 21 | } |
| 22 | // Set the sender and recipient. |
| 23 | c.Mail("sender@example.org") |
| 24 | c.Rcpt("recipient@example.net") |
| 25 | // Send the email body. |
| 26 | wc, err := c.Data() |
| 27 | if err != nil { |
| 28 | log.Fatal(err) |
| 29 | } |
| 30 | defer wc.Close() |
| 31 | buf := bytes.NewBufferString("This is the email body.") |
| 32 | if _, err = buf.WriteTo(wc); err != nil { |
| 33 | log.Fatal(err) |
| 34 | } |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 35 | } |
| 36 | ``` |
| 37 | |
| 38 | Authenticated SMTP: |
| 39 | |
| 40 | ``` |
| 41 | package main |
| 42 | |
| 43 | import ( |
| 44 | "log" |
| 45 | "net/smtp" |
| 46 | ) |
| 47 | |
| 48 | func main() { |
| 49 | // Set up authentication information. |
| 50 | auth := smtp.PlainAuth( |
| 51 | "", |
| 52 | "user@example.com", |
| 53 | "password", |
| 54 | "mail.example.com", |
| 55 | ) |
| 56 | // Connect to the server, authenticate, set the sender and recipient, |
| 57 | // and send the email all in one step. |
| 58 | err := smtp.SendMail( |
| 59 | "mail.example.com:25", |
| 60 | auth, |
| 61 | "sender@example.org", |
| 62 | []string{"recipient@example.net"}, |
| 63 | []byte("This is the email body."), |
| 64 | ) |
| 65 | if err != nil { |
| 66 | log.Fatal(err) |
| 67 | } |
| 68 | } |
| 69 | ``` |