How to send a mail with using auth?

前提是你 提交于 2020-06-17 09:40:14

问题


I'm using smtp package of golang to send the mail from localhost to the given mail address. But there is a problem I'm providing my email and password for it but it will show me the error of

535 5.7.8 Username and Password not accepted. Learn more at
5.7.8  https://support.google.com/mail/?p=BadCredentials p24sm107930499pfk.155 - gsmtp

they want that I have to allow less secure app to use my account But I don't want to allow that I tried a small piece of code for it.

Tried Example1:-

// Set up authentication information.
auth := smtp.PlainAuth(
    "",
    "email",
    "password",
    "smtp.gmail.com",
)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
err := smtp.SendMail(
    "smtp.gmail.com:25",
    auth,
    "emailFrom",
    []string{EmailToooo},
    []byte("This is the email body."),
)
if err != nil {
    log.Fatal(err)
} 

*Tried Example 2:- *

m := gomail.NewMessage()
m.SetHeader("From", "SenderEmail@gmail.com")
m.SetHeader("To", "Email_Tooo@gmail.com")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")

d := gomail.NewDialer("smtp.gmail.com", 587, "email", "password")

// Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil {
    fmt.Println(err)
}    

I also tried a gopkg.in/gomail.v2 package for doing NoAuth mail but in this it will give me the error of port connection see in given code:-

m := gomail.NewMessage()
m.SetHeader("From", "from@example.com")
m.SetHeader("To", "to@example.com")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/plain", "Hello!")

d := gomail.Dialer{Host: "localhost", Port: 587}
if err := d.DialAndSend(m); err != nil {
    panic(err)
}   

I also change the port to 8080 after doing 8080 it will not give any response it was showing only requesting.

Can anyone tell me that how will I send mail from localhost to the given mail address without auth?


回答1:


Try to use port 587 on first example. It should be working.

err := smtp.SendMail(
    "smtp.gmail.com:587",
    auth,
    "emailFrom",
    []string{EmailToooo},
    []byte("This is the email body."),
)

If you use smtp.gmail.com then the correct port is either 587 (TLS) or 465 (SSL), with the less secure app must be allowed.

Further information: https://support.google.com/a/answer/176600?hl=en



来源:https://stackoverflow.com/questions/54071379/how-to-send-a-mail-with-using-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!