dongjun111111 / blog

BLOG
36 stars 5 forks source link

Golang发送邮件类使用 #58

Open dongjun111111 opened 8 years ago

dongjun111111 commented 8 years ago

Golang发送邮件类使用

下面是一个使用网易邮件服务器发送邮件的demo,测试通过。

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

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" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}

func main() {   
    user := "user @163.com"    //发件人邮箱账号
    password := "password "    //发件人邮箱密码
    host := "smtp.163.com:25" 
    to := " to@qq.com"  //收件人邮箱账号
    subject := "Jason"          //邮件主题
    body := `
    
    
     邮件内容
    
    
    `
    fmt.Println("sending email......")
    err := SendMail(user, password, host, to, subject, body, "html")
    if err != nil {
        fmt.Println("sended mail error!")
        fmt.Println(err)
    }else{
        fmt.Println("sended mail success!")
    }
}

如果出现535 Error: authentication failed错误,请查看解决方法

playmyswift commented 7 years ago

出现过 么 554 DT:SPM 163 smtp7,C8CowABntUKgeI1ZLK5bCw--.22461S3 1502443681,please see http://mail.163.com/help/help_spam_16.htm?ip=60.194.185.2&hostid=smtp7&time=1502443681

dongjun111111 commented 7 years ago

自己好像并没有出现过,网易的错误说明很详尽呢

playmyswift commented 7 years ago

我找到原因了, 网上的教程都是说多个邮件用";" 分割, 其实一发送就会报错, 说是垃圾邮件, 应该用 ","

playmyswift commented 7 years ago

太坑了

dongjun111111 commented 7 years ago

按照你说的,有成功发送吗

playmyswift commented 7 years ago

成功发送

0x457 commented 6 years ago

good!!!

cqzhen commented 5 years ago

@ericjjj 👍