This is the 22nd day of my participation in Gwen Challenge
Use GOLANG to send emails
Let’s review the captcha case of GO we talked about last time
- Verification code type sorting
- Installation of the verification code library
- Verification code library source code introduction
- Practical operation, coding
- Verification code effect display
Want to see how GO do captcha, welcome to see the article GO captcha case
In life and work, we are inseparable from the sending and receiving of emails, or check and send on the mobile phone, or in front of their own computer for email editing and processing
However, we will find that most of the time, we have to send a certain type of mail at the same time every day, and the content is similar.
And, sometimes because of a variety of reasons, can not send the mail on time, at this time, if we can write a customized mail program that can be said to be very fragrant
So, let’s start with some common sense
What’s the mail?
Mail is a document processed by means of transfer
The process by which mail is delivered is called post, and the organization or system that provides mail services is called post
There are two types of mail: domestic mail and international mail
So what is E-mail?
E-mail is a form of communication that provides the exchange of information electronically. It is the most widely used service on the Internet
What are the advantages of email?
E-mail The web-based E-mail system has the following advantages:
- The price is very low
No matter where you send it, you only have to pay for the Internet
- Transport fast
Within seconds, it can be sent to any designated destination in the world, connecting with web users anywhere in the world
What is the format of E-mail?
- The text
- image
- Voice etc.
Think about the steps you need to go through every time you send an email
- Open the computer
- Enter the browser
- Open email
- New-edit-Send
Most of it is copy-pasted,
GOLang is a great tool to use to send emails
E-mail protocol
When we use programming language, we need to follow the programming language specification, and when we browse the web in the browser, we need to follow various network protocols
Well, we email senders must also know what email protocols are available. Let’s list them
- SMTP
SMTP is a simple mail transfer protocol. It is a set of specifications used to transfer mails from source addresses to destination addresses. It controls the mail transfer mode
In addition, SMTP belongs to TCP/IP protocol cluster
- POP3
Version 3 of the Post Office Protocol, the first offline protocol standard for Internet E-mail
- IMAP
Is a new protocol that is superior to POP
Like POP, IMAP can download messages, delete messages from the server, or ask if there are new messages
IMAP allows users to create and manage mail folders or mailboxes, delete messages, and query some or all of the contents of a letter on the server
All of this can be done without the need to download mail from the server to the user’s PC
OK, let’s start coding
Start coding emails
Let’s use SMTP protocol to send mail today, there are several steps
- Above QQ mailbox, get authorization code
- Code and install
email
Mail library - Start sending emails
inQQ
From the mailbox. Get the authorization code
- Enter the
QQ
Email, clickSettings -> Account
- Down the page, see the POP3 / IMAP/SMTP/Exchange/CardDAV/CalDAV service
- open
POP3/SMTP
service - open
IMAP/SMTP
service - Generate the authorization code, the authorization code itself to find a place to save
Code and installemail
Mail library
Let’s write this mail small case, use GO package is “github.com/jordan-wright/email”, we can manually install
go get github.com/jordan-wright/email
Copy the code
No manual installation is also no problem, we can now look at writing a first version of the small case of sending mail
package main
import (
"github.com/jordan-wright/email"
"log"
"net/smtp"
)
func main(a) {
// Simply set the log parameter
log.SetFlags(log.Lshortfile | log.LstdFlags)
em := email.NewEmail()
// Set sender's email address
em.From = "xx <[email protected]>"
// Set receiver's email address // Set receiver's email address
em.To = []string{"[email protected]"}
// Set the theme
em.Subject = "The little devil boy sent you an E-mail."
// Simply set the content of the file to be sent, temporarily set to plain text
em.Text = []byte("Hello world, let's use Golang to send an email!!")
// Set the server configuration
err := e.Send("smtp.qq.com:25", smtp.PlainAuth(""."My own email account"."Authorization code for your email address"."smtp.qq.com"))
iferr ! =nil {
log.Fatal(err)
}
log.Println("send successfully ... ")}Copy the code
The effect of running the above code is as follows:
2021/06/xx xx:36:28 main.go:28: send successfully ...
Copy the code
Let’s have a look at our mailbox
Sure enough, it was a success
So that’s it for today’s article sharing, when you ask, I want to post, I want to posthtml
Content, I want to send attachments, I even want to secretly cc some people
Good arrangement
sendHTML
Content + Attachment
Let’s take a look at which fields the library supports. The NewEmail method above returns a pointer
// NewEmail creates an Email, and returns the pointer to it.
func NewEmail(a) *Email {
return &Email{Headers: textproto.MIMEHeader{}}
}
Copy the code
This pointer points to a mail data structure. Let’s take a look
// Email is the type used for email messages
type Email struct {
ReplyTo []string
From string / / the sender
To []string / / the recipient
Bcc []string / / send
Cc []string / / cc
Subject string / / theme
Text []byte // Plaintext message (optional)
HTML []byte // Html message (optional)
Sender string // override From as SMTP envelope sender (optional)
Headers textproto.MIMEHeader / / agreement
Attachments []*Attachment / / accessories
ReadReceipt []string
}
Copy the code
Look at the above structure, we can send mail, cc, BCC, add attachments, or send HTML content, let’s change the above code
func main(a) {
// simply set the l og parameter
log.SetFlags(log.Lshortfile | log.LstdFlags)
em := email.NewEmail()
// Set the sender's mailbox
em.From = "xx <[email protected]>"
// Set the recipient's mailbox
em.To = []string{"[email protected]"}
/ / cc
em.Cc = []string{"[email protected]"}
/ / send
em.Bcc = []string{"[email protected]"}
// Set the theme
em.Subject = "The little devil boy sent you an E-mail."
// Set the content of the file to be sent
em.HTML = []byte(` < h3 > < a href = "https://juejin.cn/user/3465271329953806" > welcome to small familiars which zha home page < / a > < / h3 > < br / > < table border = "0" Style =" max-width: 100%; clear: both; min-height: 1em; Cellpadding = "3 px" > < tr > < td > 1 < / td > < td > < a href = "https://juejin.cn/post/6975686540601245709" > GO defer implementation principle in < / a > < / td > < / tr > < tr > < td > 2 < / td > < td > < a href = "https://juejin.cn/post/6975280009082568740" > GO in Chan principle share < / a > < / td > < / tr > < tr > 3 < / td > < td > < td > < a href = "https://juejin.cn/post/6974908615232585764" > GO map in the implementation of the principle of < / a > < / td > < / tr > < tr > < td > 4 < / td > < td > < a href = "https://juejin.cn/post/6974539862800072718" > GO slice in the implementation of the principle of < / a > < / td > < / tr > < tr > < td > 5 < / td > < td > < a Href = "https://juejin.cn/post/6974169270624190495" > GO string in the implementation of the principle of < / a > < / td > < / tr > < tr > < td > 6 < / td > < td > < a Href = "https://juejin.cn/post/6973793593987170317" > GO ETCD coding in case share < / a > < / td > < / tr > < tr > < td > 7 < / td > < td > < a Href = "https://juejin.cn/post/6973455825905909797" > service registration and discovery of ETCD < / a > < / td > < / tr > < tr > < td > 8 < / td > < td > < a Href = "https://juejin.cn/post/6973108979777929230" > GO channel, and sharing of sync bag < / a > < / td > < / tr > < tr > < td > 9 < / td > < td > < a Href = "https://juejin.cn/post/6972846349968474142" > GO lock and atomic operation share < / a > < / td > < / tr > < / table > `)
// Add attachments
em.AttachFile("./test.html")
// Set the server configuration
err := e.Send("smtp.qq.com:25", smtp.PlainAuth(""."My own email account"."Authorization code for your email address"."smtp.qq.com"))
iferr ! =nil {
log.Fatal(err)
}
log.Println("send successfully ... ")}Copy the code
Once it’s up and running, let’s check email
Cc, BCC, add attachments, send HTML content, all on top
How can I improve the performance of sending emails
The get github.com/jordan-wright/email package provides a connection pool for us, which you can say is not sweet, we can reuse the last network connection to send email, rather than each time we send email, establish a connection
We all know that building connections takes time and resources, so we need to optimize as much as possible
In another DEMO, connection pooling, let’s use connection pooling to create a channel with five buffers, and let three coroutines go to the channel to fetch data and send emails
func main(a) {
// simply set the l og parameter
log.SetFlags(log.Lshortfile | log.LstdFlags)
// Create a channel with 5 buffers and the data type is * email.email
ch := make(chan *email.Email, 5)
/ / the connection pool
p, err := email.NewPool(
"smtp.qq.com:25".3.// Set the number to 3
smtp.PlainAuth(""."My own email"."Authorization code for your email address"."smtp.qq.com"),iferr ! =nil {
log.Fatal("email.NewPool error : ", err)
}
// sync package to control synchronization
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(a) {
defer wg.Done()
// If ch has no data, block; if ch is closed, exit the loop
for e := range ch {
// The timeout is 10 seconds
err := p.Send(e, 10*time.Second)
iferr ! =nil {
log.Printf( "p.Send error : %v , e = %v , i = %d\n", err , e, i)
}
}
}()
}
for i := 0; i < 5; i++ {
e := email.NewEmail()
// Set the basic information for sending emails
e.From = "xx <[email protected]>"
e.To = []string{"[email protected]"}
e.Subject = "test email.NewPool " + fmt.Sprintf(" the %d email",i)
e.Text = []byte(fmt.Sprintf("test email.NewPool , the %d email !", i))
ch <- e
}
// Close the channel
close(ch)
// Wait for the subcoroutine to exit
wg.Wait()
log.Println("send successfully ... ")}Copy the code
After running the above code, let’s check the mailbox
As you can see, the emails are not sent in order, that’s right
If you have any questions about using Sync above, please check out the GO channel and sync package sharing article
conclusion
- Shared email. What is email
- What are the mail protocols
- How do I use GOLANG to send email
- How to send an email with plain text,
HTML
Contents, attachments, etc - How to cc or BCC an email
- How can I improve the performance of sending emails
GOLANG how to send email (QQ mailbox) | Go theme month
Welcome to like, follow and favorites
Friends, your support and encouragement, I insist on sharing, improve the quality of the power
Well, that’s it for now, and next time share a wave of GO crawlers
Technology is open, our mentality, should be more open. Embrace change, live in the sun, and strive to move forward.
I am Nezha, welcome to like, see you next time ~