Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Sending Mail |
| 2 | |
Alexandre Cesaro | 4980e25 | 2015-09-08 14:08:24 +0200 | [diff] [blame] | 3 | See also: |
| 4 | * [net/smtp](http://golang.org/pkg/net/smtp/) |
| 5 | * [Email packages](https://github.com/golang/go/wiki/Projects#email) |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 6 | |
| 7 | Streaming the body: |
| 8 | |
bom-d-van | daa324d | 2015-01-03 22:21:18 -0800 | [diff] [blame] | 9 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 10 | package main |
| 11 | |
| 12 | import ( |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 13 | "bytes" |
| 14 | "log" |
| 15 | "net/smtp" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 16 | ) |
| 17 | |
| 18 | func main() { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 19 | // Connect to the remote SMTP server. |
| 20 | c, err := smtp.Dial("mail.example.com:25") |
| 21 | if err != nil { |
| 22 | log.Fatal(err) |
| 23 | } |
miffedmap | 51a2e41 | 2015-02-26 20:32:41 +0200 | [diff] [blame] | 24 | defer c.Close() |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 25 | // 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 Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 38 | } |
| 39 | ``` |
| 40 | |
| 41 | Authenticated SMTP: |
| 42 | |
bom-d-van | daa324d | 2015-01-03 22:21:18 -0800 | [diff] [blame] | 43 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 44 | package main |
| 45 | |
| 46 | import ( |
| 47 | "log" |
| 48 | "net/smtp" |
| 49 | ) |
| 50 | |
| 51 | func 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 | ``` |