Can I Send Emails in Go Without Using an SMTP Server?

DDD
Release: 2024-10-25 20:27:02
Original
991 people have browsed it

Can I Send Emails in Go Without Using an SMTP Server?

Sending Emails Without an SMTP Server in Go

Question:

You want to send bulk emails without relying on an external SMTP server due to usage limitations. Can you send emails without an SMTP server using Go's standard library?

Answer:

To send emails without an SMTP server, you must delegate the task to another program capable of sending emails. In POSIX systems, the /usr/sbin/sendmail program is often available for this purpose. You can call it with the -t option to retrieve recipient addresses from the message's To headers.

Using the Standard Library with Sendmail

You can use the os/exec, net/mail, and net/textproto packages to call Sendmail directly, but the gomail package provides a simpler solution. Its Message type includes a WriteTo() method that can write to a running Sendmail instance. Here's an example:

<code class="go">import (
    "os/exec"

    "github.com/go-gomail/gomail"
)

const sendmailPath = "/usr/sbin/sendmail"

func sendEmail(m *gomail.Message) error {
    cmd := exec.Command(sendmailPath, "-t")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return err
    }

    if err := cmd.Start(); err != nil {
        return err
    }

    if _, err := m.WriteTo(stdin); err != nil {
        return err
    }

    if err := stdin.Close(); err != nil {
        return err
    }

    if err := cmd.Wait(); err != nil {
        return err
    }

    return nil
}</code>
Copy after login

Advantages of Using an MTA:

While using an MTA may seem like an extra step, it offers the advantage of mail queuing. If an MTA cannot deliver a message immediately, such as during a network outage, it will store the message in a queue and repeatedly attempt to deliver it until successful or a timeout occurs.

The above is the detailed content of Can I Send Emails in Go Without Using an SMTP Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!