blob: 67ee7008143ad019dfe17e933c20d59b5f2a287a [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001# Sending Mail
2
3See also: http://golang.org/pkg/net/smtp/
4
5Streaming the body:
6
7```
8package main
9
10import (
Dave Day0d6986a2014-12-10 15:02:18 +110011 "bytes"
12 "log"
13 "net/smtp"
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110014)
15
16func main() {
Dave Day0d6986a2014-12-10 15:02:18 +110017 // 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 Gerrand5bc444d2014-12-10 11:35:11 +110035}
36```
37
38Authenticated SMTP:
39
40```
41package main
42
43import (
44 "log"
45 "net/smtp"
46)
47
48func 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```