Created
September 22, 2020 05:48
-
-
Save rammanokar/5dd2d9ee26df50dd1f4fad326b25a377 to your computer and use it in GitHub Desktop.
send office 365 mail using go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "net" | |
| "errors" | |
| mail "net/mail" | |
| smtp "net/smtp" | |
| ) | |
| type loginAuth struct { | |
| username, password string | |
| } | |
| func LoginAuth(username, password string) smtp.Auth { | |
| return &loginAuth{username, password} | |
| } | |
| func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { | |
| return "LOGIN", []byte{}, nil | |
| } | |
| func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { | |
| if more { | |
| switch string(fromServer) { | |
| case "Username:": | |
| return []byte(a.username), nil | |
| case "Password:": | |
| return []byte(a.password), nil | |
| default: | |
| return nil, errors.New("Unknown fromServer") | |
| } | |
| } | |
| return nil, nil | |
| } | |
| func main() { | |
| from := mail.Address{"", "example@example.com"} | |
| to := mail.Address{"", "example@example.com"} | |
| subject := "My test subject" | |
| body := "Test email body" | |
| headers := make(map[string]string) | |
| headers["From"] = from.String() | |
| headers["To"] = to.String() | |
| headers["Subject"] = subject | |
| message := "" | |
| for k, v := range headers { | |
| message += fmt.Sprintf("%s: %s\r\n", k, v) | |
| } | |
| message += "\r\n" + body | |
| tlsconfig := &tls.Config{ | |
| ServerName: host, | |
| } | |
| conn, err := tls.Dial("tcp", "smtp.office365.com:587", tlsconfig) | |
| if err != nil { | |
| fmt.Println("tls.Dial Error: ", err) | |
| } | |
| c, err := smtp.NewClient(conn, host) | |
| if err != nil { | |
| fmt.Println("smtp.NewClient Error: ", err) | |
| } | |
| if err = c.Auth(LoginAuth("example@example.com", "password")); err != nil { | |
| fmt.Println("c.Auth Error: ", err) | |
| return | |
| } | |
| if err = c.Mail(from.Address); err != nil { | |
| fmt.Println("c.Mail Error: ", err) | |
| } | |
| if err = c.Rcpt(to.Address); err != nil { | |
| fmt.Println("c.Rcpt Error: ", err) | |
| } | |
| w, err := c.Data() | |
| if err != nil { | |
| fmt.Println("c.Data Error: ", err) | |
| } | |
| _, err = w.Write([]byte(message)) | |
| if err != nil { | |
| fmt.Println("Error: ", err) | |
| } | |
| err = w.Close() | |
| if err != nil { | |
| fmt.Println("reader Error: ", err) | |
| } | |
| c.Quit() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment