Golang "crashes" using smtp.SendMail(

I have a website using Golang as “Apache”.

http.ListenAndServe(“:9090”, nil) <----- starts the website

In this website I have a form that I submit a mail using smtp.SendMail.

  1. Sending a “valid” mail address works perfect

  2. Sending a “valid” mail address sometimes returns “550 5.7.1 SPF failed. Domain test.com is not allowed to send mail from (IP-address)”

  3. Sending a “nonsense” mail address (test) fails and report “501 5.1.7 Bad sender address syntax”

     mailfrom = "test@company.se" <--- VALID mail address
    
     auth := smtp.PlainAuth("", "sibert@gmail.com", "password", "smtp.gmail.com")
     from := (mailfrom)
     to := []string{"sibert@gmail.com"}
     msg := []byte("From: " + mailfrom + "\r\n" +
     	"To: support@company.com\r\n" +
     	"Subject: Test\r\n" +
     	"testmail\r\n" +
     	(mailfrom))
     err := smtp.SendMail("smtp.gmail.com:587", auth, from, to, msg)
     if err != nil {
     	log.Fatal(err)
     }
    }
    

There is two problem:

  1. How can I trap this and send “sorry not delivered” to the user?
  2. How can I prevent “http.ListenAndServe” to crash when Go do not like the mail address?
1 Like

Do not log fatally, it implies a panic.

1 Like

How should I do?

1 Like

well, log error or less.

1 Like

Thank you! This solved the problem.

if err != nil {
	return ("sorry.html")
}
return ("thanks.html")
1 Like

I have no clue what the function is meant to do, but for me it seems wrong that it returns the name of an HTML document, when it is supposed to send an email…

Also usually you want to log errors and their cause, users could try to find weak points in your software.

Last but not least, return is not a function and does not need parenthesis…

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.