send mail in go

Here's an example Go program that sends an email using the SMTP protocol:

main.go
package main

import (
    "net/smtp"
    "net/mail"
    "fmt"
)

func main() {
    // Set up authentication information.
    auth := smtp.PlainAuth("", "your_email@example.com", "your_password", "smtp.example.com")

    // Set up the email message.
    from := mail.Address{"Sender Name", "your_email@example.com"}
    to := mail.Address{"Recipient Name", "recipient_email@example.com"}
    subject := "Test Email"
    body := "This is a test email from Go."

    message := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",
        from.String(),
        to.String(),
        subject,
        body)

    // Send the email message.
    err := smtp.SendMail("smtp.example.com:587", auth, from.Address, []string{to.Address}, []byte(message))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Email sent successfully!")
}
862 chars
33 lines

This program uses the net/smtp package to authenticate with an SMTP server, and the net/mail package to set up the email message. The fmt package is used to format the email message as a string.

To use this program, replace the placeholders for the email sender and recipient addresses, authentication information, and SMTP server hostname and port number.

related categories

gistlibby LogSnag