【go语言发送电子邮件】go语言版发送电子邮件

一、实现功能
用go语言发送一封邮件

二、实现源代码

package main
import (
    "net/smtp"
    "fmt"
    "strings"
)

/*
 *  user : example@example.com login smtp server user
 *  password: xxxxx login smtp server password
 *  host: smtp.example.com:port   smtp.163.com:25
 *  to: example@example.com;example1@163.com;example2@sina.com.cn;...
 *  subject:The subject of mail
 *  body: The content of mail
 *  mailtyoe: mail type html or text
 */

func SendMail(user, password, host, to, subject, body, mailtype string) error{
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    var content_type string
    if mailtype == "html" {
        content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
    }else{
        content_type = "Content-Type: text/plain" + "; charset=UTF-8"
    }

    msg := []byte("To: " + to + "\r\nFrom: " + user + "<"+ user +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}

func main() {
    user := "此处填写qq邮箱账号"
    password := "此处填写qq邮箱授权码"
    host := "smtp.qq.com:587"
    to := "18720081236m@sina.cn"
    subject := "Test send email by golang"

    body := `
`
    fmt.Println("send email")
    err := SendMail(user, password, host, to, subject, body, "text")
    if err != nil {
        fmt.Println("send mail error!")
        fmt.Println(err)
    }else{
        fmt.Println("send mail success!")
    }

}


运行效果

"D:\Program Files (x86)\JetBrains\Gogland 171.3780.106\bin\runnerw.exe" D:/Go\bin\go.exe run D:/Go/code/src/awesomeProject/go_email.go
send email
send mail success!

Process finished with exit code 0

版本2(发送多个人 ,HTML格式):

package main
import (
    "net/smtp"
    "fmt"
    "strings"
)

/*
 *  user : example@example.com login smtp server user
 *  password: xxxxx login smtp server password
 *  host: smtp.example.com:port   smtp.163.com:25
 *  to: example@example.com;example1@163.com;example2@sina.com.cn;...
 *  subject:The subject of mail
 *  body: The content of mail
 *  mailtyoe: mail type html or text
 */

func SendMail(user, password, host, to, subject, body, mailtype string) error{
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    var content_type string
    if mailtype == "html" {
        content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
    }else{
        content_type = "Content-Type: text/plain" + "; charset=UTF-8"
    }

    msg := []byte("To: " + to + "\r\nFrom: " + user + "<"+ user +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}

func main() {
    user := "1973536419@qq.com"
    password := "XXXXXXXX"
    host := "smtp.qq.com:587"
    to := "defa.lai@cgtz.com;fang.chen@lg-finance.com";


    subject := "Test send email by golang"

    body := `
    <!DOCTYPE html>
        <html>
        <body>
        <div style="text-align:center;width:78.78%;padding: 8px; line-height: 1.42857; vertical-align: top; border-top-width: 1px; border-top-color: rgb(221, 221, 221); background-color: #28a745;color:#fff"><strong>用户工资数据报表</strong></div>

            <table border="1" style="width:80%;">
          <tr style="background-color:pink;text-align:center;">
            <th>月份</th>
            <th>存款</th>
            <th>工资</th>
            <th>年薪</th>


          </tr>
          <tr  style="text-align:center;">
            <td>一月</td>
            <td>1000 元</td>
            <td>3000 元</td>
            <td>12000元</td>

          </tr>
          <tr  style="text-align:center;">
            <td>二月</td>
            <td>1500 元</td>
            <td>4000 元</td>
            <td>16000 元</td>
          </tr>
        </table>

        </body>
        </html>


    `
    fmt.Println("send email")
    err := SendMail(user, password, host, to, subject, body, "html")
    if err != nil {
        fmt.Println("send mail error!")
        fmt.Println(err)
    }else{
        fmt.Println("send mail success!")
    }

}

这里写图片描述

已标记关键词 清除标记
<div class="post-text" itemprop="text"> <p>I'm trying to send an e-mail in Golang and I have a lot of problems with it. I'm new in Go so maybe this is very simply but I cannot find the answer on the doc.</p> <p>This is what I want to do: 1. get an e-mail from the STDIN 2. parse the e-mail (getting from, to, subject, attachments and so on) 3. send this e-mail (put it again to the queue in local postfix)</p> <p>I did 1 and 2 but I have a problem with 3th one.</p> <p>This is what I have now:</p> <pre><code>package main import ( "fmt" "github.com/jhillyerd/go.enmime" //"github.com/sendgrid/sendgrid-go" "net/smtp" "github.com/jordan-wright/email" "os" "net/mail" "io/ioutil" "bytes" ) func main() { mail_stdin, err := ioutil.ReadAll(os.Stdin) if err != nil { return } // Convert type to io.Reader buf := bytes.NewBuffer(mail_stdin) msg, err := mail.ReadMessage(buf) if err != nil { return } mime, err := enmime.ParseMIMEBody(msg) if err != nil { return } # saving attachments for _, value := range mime.Attachments { fmt.Println(value.FileName()) err := ioutil.WriteFile(value.FileName(), value.Content(), 0664) if err != nil { //panic(err) return } fmt.Printf("From: %v ", msg.Header.Get("From")) fmt.Printf("Subject: %v ", mime.GetHeader("Subject")) fmt.Printf("Text Body: %v chars ", len(mime.Text)) fmt.Printf("HTML Body: %v chars ", len(mime.Html)) fmt.Printf("Inlines: %v ", len(mime.Inlines)) fmt.Printf("Attachments: %v ", len(mime.Attachments)) fmt.Println(mime.Attachments) fmt.Println(mime.OtherParts) fmt.Printf("Attachments: %v ", mime.Attachments) } </code></pre> <p>I already did few tests using: net/smtp, sendgrid-go and jordan-wright/email. All I want to do is to send an e-mail (without changing anything) from the server to the queue again. Most of those modules needs to have Auth, but I just want to simply send is using sendmail, in the same way as I can do this from the bash:</p> <pre><code># echo "test" | mail {address} </code></pre> </div>
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页