Skip to content

Instantly share code, notes, and snippets.

@narukoshin
Last active August 30, 2021 18:43
Show Gist options
  • Save narukoshin/6dc307d842b023bd49242ea7d8000360 to your computer and use it in GitHub Desktop.
Save narukoshin/6dc307d842b023bd49242ea7d8000360 to your computer and use it in GitHub Desktop.
Send SMTP email with Go
package main
import (
"crypto/tls"
"errors"
"log"
"net"
"net/smtp"
"strings"
)
type loginAuth struct {
username, password string
}
func main(){
// Creating the variables
var (
Server, Port string = "smtp-mail.outlook.com", "587"
Subject string
Recipients []string
Name string
Email string
Pass string
Message string
)
/**! Setting the variables !**/
// Setting some fucking variables about myself
Name = "Naru Koshin"
Email = "naru.koshin@outlook.jp"
Pass = "HighlyConfidential"
// Setting the email
Recipients = []string{"naru.koshin@outlook.jp"}
Subject = "Test Email"
Message = "Hello, this is my test message"
// Creating connection to the fucking mail server
conn, err := net.Dial("tcp", Server + ":" + Port)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Creating the fucking client
client, err := smtp.NewClient(conn, Server)
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Testing the fucking connection
err = client.Hello(Server)
if err != nil {
log.Fatal(err)
}
// TLS shit
tls := &tls.Config {
InsecureSkipVerify: true,
}
// Starting some TLS Shit
err = client.StartTLS(tls)
if err != nil {
log.Fatal(err)
}
// Making auth
auth := LoginAuth(Email, Pass)
err = client.Auth(auth)
if err != nil {
log.Fatal(err)
}
// Setting the mail sender
err = client.Mail(Email)
if err != nil {
log.Fatal(err)
}
// Setting the mail recipients
for _, e := range Recipients {
err = client.Rcpt(e)
if err != nil {
log.Fatal(err)
}
}
// Making the message body
data, err := client.Data()
if err != nil {
log.Fatal(err)
}
defer data.Close()
// Writting the emai headers
reps := strings.Join(Recipients, ",")
data.Write([]byte("To: "+reps+"\r\nFrom: "+Name+" <"+Email+">\r\nSubject: "+Subject+"\r\n\r\n" + Message))
// Sending the message
err = client.Quit()
if err != nil {
log.Fatal(err)
}
}
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("smtp: unknown from server")
}
}
return nil, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment