-
Notifications
You must be signed in to change notification settings - Fork 2
/
testemail.go
102 lines (80 loc) · 1.83 KB
/
testemail.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"crypto/tls"
"fmt"
"log"
"net/smtp"
)
type Mail struct {
senderId string
toId string
subject string
body string
}
type SmtpServer struct {
host string
port string
}
func (s *SmtpServer) ServerName() string {
return s.host + ":" + s.port
}
func (mail *Mail) BuildMessage() string {
message := ""
message += fmt.Sprintf("From: %s\r\n", mail.senderId)
message += fmt.Sprintf("To: %s\r\n", mail.toId)
message += fmt.Sprintf("Subject: %s\r\n", mail.subject)
message += "\r\n" + mail.body
return message
}
func sendTheMail() {
mail := Mail{}
mail.senderId = "from@email.duh"
mail.toId = "to@email.dur"
mail.subject = "This is the email subject"
mail.body = "Harry Potter and threat to Israel\n\nGood editing!!"
messageBody := mail.BuildMessage()
smtpServer := SmtpServer{host: "smtp.gmail.com", port: "465"}
log.Println(smtpServer.host)
//build an auth
auth := smtp.PlainAuth("", mail.senderId, "hackmeplease", smtpServer.host)
// Gmail will reject connection if it's not secure
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: smtpServer.host,
}
conn, err := tls.Dial("tcp", smtpServer.ServerName(), tlsconfig)
if err != nil {
log.Panic(err)
}
client, err := smtp.NewClient(conn, smtpServer.host)
if err != nil {
log.Panic(err)
}
// step 1: Use Auth
if err = client.Auth(auth); err != nil {
log.Panic(err)
}
// step 2: add all from and to
if err = client.Mail(mail.senderId); err != nil {
log.Panic(err)
}
if err = client.Rcpt(mail.toId); err != nil {
log.Panic(err)
}
// Data
w, err := client.Data()
if err != nil {
log.Panic(err)
}
_, err = w.Write([]byte(messageBody))
if err != nil {
log.Panic(err)
}
err = w.Close()
if err != nil {
log.Panic(err)
}
client.Quit()
log.Println("Mail sent successfully")
}