Marc Kenneth Lomio
Marc Kenneth Lomio

Reputation: 439

Send email in gmail account using SMTP

I want to send an test email to my Gmail account

Thus, I tried this snippet from https://golang.org/src/net/smtp/example_test.go

func ExampleSendMail() {
    // Set up authentication information.
    auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")

    // Connect to the server, authenticate, set the sender and recipient,
    // and send the email all in one step.
    to := []string{"recipient@example.net"}
    msg := []byte("To: recipient@example.net\r\n" +
        "Subject: discount Gophers!\r\n" +
        "\r\n" +
        "This is the email body.\r\n")
    err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
    if err != nil {
        log.Fatal(err)
    }
}

However. I get this error messsage.

dial tcp 74.125.23.109:25: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Help me to understand what is the root cause of this problem.

Upvotes: 1

Views: 780

Answers (1)

Ezequiel Muns
Ezequiel Muns

Reputation: 7762

I'm going to assume that in your actual code you're using a real server domain and port instead of mail.example.com.

From the error message it's clear that the SMTP server that you tried to connect to did not respond and your request timed out. You've got to make sure you are contacting a valid SMTP server at the right port (the mail.example.com:25 part in the SendMail call).

One simple way to check would be to go to your terminal and run:

telnet server.anexampledomain.net 25   # replace with domain and port in question

See if you get an answer like:

Trying 74.125.23.109...
Connected to 74.125.23.109.
Escape character is '^]'.
220 smtp.gmail.com ESMTP x3sm2050129pfp.98 - gsmtp

That tells you the server is accessible and open to SMTP connections.

If you've written the right server domain and port, and you can't contact the server with the above then the problem is with your network and not the code you've written.

Upvotes: 3

Related Questions