github.com/serge-v/zero@v1.0.2-0.20220911142406-af4b6a19e68a/examples/how-to-send-mail/index.html (about) 1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <title>golang-email</title> 5 <link rel="stylesheet" href="main.css"> 6 <meta name="viewport" content="width=device-width,initial-scale=1"> 7 </head> 8 <body> 9 10 <h1>How to send email from golang app</h1> 11 12 <time>30 July 2021</time> 13 <p>In this example we will send email using gmail server <code>smtp.gmail.com</code>.</p> 14 15 <h2>Copy functions</h2> 16 17 <p>Put next functions into <code>smtp.go</code> file.</p> 18 19 <gocode> 20 // sendEmail formats and sends an email. 21 func sendEmail(from, to, subject, body string) error { 22 23 // encode subject because it can be in different languages 24 subject = mime.QEncoding.Encode("utf-8", subject) 25 26 // create message in valid format 27 msg := "From: " + from + "\n" 28 msg += "To: " + to + "\n" 29 msg += "Subject: " + subject + "\n\n" 30 msg += body + "\n" 31 32 if err := smtpSend(from, []string{to}, []byte(msg)); err != nil { 33 return fmt.Errorf("smtp send: %w", err) 34 } 35 return nil 36 } 37 38 // smtpSend sends an email using smtp.gmail.com. 39 func smtpSend(from string, to []string, message []byte) error { 40 user := os.Getenv("SMTP_USER") 41 pass := os.Getenv("SMTP_PASSWORD") 42 if user == "" || pass == "" { 43 return fmt.Errorf("invalid credentials") 44 } 45 46 // create authentication to login to smtp.gmail.com. 47 auth := smtp.PlainAuth("", user, pass, "smtp.gmail.com") 48 49 err := smtp.SendMail("smtp.gmail.com:587", auth, from, to, message) 50 if err != nil { 51 return fmt.Errorf("sendmail: %w", err) 52 } 53 54 return nil 55 } 56 57 </gocode> 58 59 <h2>Configuration</h2> 60 61 <p>Add to your <code>run</code> file:</p> 62 63 <gocode> 64 set SMTP_USER=[I will give you a user name] 65 set SMTP_PASSWORD=[I will give you a password] 66 67 </gocode> 68 <p>Also you will need to add the same parameters to digital ocean environment.</p> 69 70 <h2>Usage</h2> 71 72 <p>In the place where you want to send the email add:</p> 73 74 <gocode> 75 from := "news sender" 76 to := "milla@someserver.com" 77 subject := "Today news" 78 body := "Hello, this is today news." 79 80 err := sendEmail(from, to, subject, body) 81 if err != nil { 82 log.Println("cannot send email:", err) 83 } 84 85 </gocode> 86 87 <h2>Quiz</h2> 88 89 <p>What imports do you need to add to smtp.go?</p> 90 91 <gocode> 92 package main 93 94 import ( 95 ??? <-- here 96 ) 97 98 </gocode> 99 100 101 <br><br><br> 102 103 <h2>The End</h2> 104 105 </body> 106 </html>