Skip to content

Instantly share code, notes, and snippets.

@devhindo
Created July 5, 2024 05:34
Show Gist options
  • Save devhindo/b9dbab6b52f8b79542a1dd70e5566413 to your computer and use it in GitHub Desktop.
Save devhindo/b9dbab6b52f8b79542a1dd70e5566413 to your computer and use it in GitHub Desktop.
send outlook mails using Go
package main
import (
"errors"
"fmt"
"log"
"net/smtp"
)
func SendMail(to string) error {
subject := "Subject: Your Subject Here\n"
body := "your mail content"
message := []byte(subject + "\n" + body)
auth := LoginAuth("yourMailAddress", "yourAppPassword") // not your real password: search creating app password in outlook
err := smtp.SendMail("smtp-mail.outlook.com:587", auth, "yourMailAddress", []string{to}, message) // "to" variable is a slice for multiple recipients
if err != nil {
fmt.Println("Error sending mail: ", err)
return err
}
log.Println("Mail sent successfully")
return nil
}
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(a.username), 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("unkown fromServer")
}
}
return nil, nil
}
func main() {
SendMail("recipient_mail")
}
/*
recommended: include all variables in .env file
ofc you should customize the content and subject as you like.
based on: https://gist.github.com/homme/22b457eb054a07e7b2fb which is based on https://gist.github.com/andelf/5118732
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment