Golang实现无需身份验证发送电子邮件的方法

Golang实现无需身份验证发送电子邮件的方法 你好 能否告诉我如何编写Go程序来发送无需SMTP认证的邮件, 谢谢

func main() {
    fmt.Println("hello world")
}
4 回复

我建议使用这个包:https://github.com/go-mail/mail

更多关于Golang实现无需身份验证发送电子邮件的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你是不想对应用程序进行身份验证,还是不想让应用程序对邮件服务器进行身份验证?

如果是前者,就像身份验证一样,但你可以跳过要求输入密码等特定部分。

如果是后者,我希望你找不到允许这样做的服务……

smtp.SendMail 接受一个可选的 smtp.Auth 参数。您可以将其设置为 nil

package main
  
import (
    "fmt"
    "net/smtp"
)       

func main() {
    msg := []byte("To: to@example.com\r\n" +
        "Subject: Hi there!\r\n" +
        "Content-Type: text/plain; charset=UTF-8\r\n" +
        "\r\n" +                      
        "Hi!\r\n")                            
    to := make([]string, 1)                       
    to[0] = "to@example.com"                          
    err := smtp.SendMail("smtp.example.com:25",
      nil /* this is the optional Auth */,
      "from@example.com", to, msg)
    fmt.Println(err)                                          
} 

在Go语言中,可以通过标准库net/smtp实现无需SMTP身份验证的邮件发送。这种方式通常适用于本地SMTP服务器(如Postfix或Sendmail)配置为允许本地无认证中继的情况。

以下是一个完整的示例,展示如何通过localhost:25发送无需认证的电子邮件:

package main

import (
    "net/smtp"
    "strings"
)

func main() {
    // 邮件发送参数
    from := "sender@example.com"
    to := []string{"recipient@example.com"}
    subject := "Test Subject"
    body := "This is a test email body."

    // 构建邮件内容
    msg := "From: " + from + "\n" +
           "To: " + strings.Join(to, ",") + "\n" +
           "Subject: " + subject + "\n\n" +
           body

    // 发送邮件(无需认证)
    err := smtp.SendMail(
        "localhost:25", // SMTP服务器地址
        nil,            // 身份验证信息设为nil
        from,           // 发件人
        to,             // 收件人列表
        []byte(msg),    // 邮件内容
    )

    if err != nil {
        panic(err)
    }
}

关键点说明:

  1. smtp.SendMail的第二个参数为nil,表示不进行身份验证
  2. SMTP服务器地址设为localhost:25,假设本地运行了允许无认证中继的SMTP服务
  3. 邮件内容需要手动构建符合RFC 5322标准的格式

注意:这种方法仅适用于本地或受信任网络环境中的SMTP服务器。在生产环境中,公开的SMTP服务器通常要求身份验证以防止滥用。

回到顶部