如何从Go发送电子邮件

时间:2015-07-07 15:18:40

标签: email parsing go

我正在尝试在Golang发送一封电子邮件,但我遇到了很多问题。我是Go的新手,所以也许这很简单,但我找不到文档上的答案。

这就是我想要做的: 1.从STDIN收到一封电子邮件 2.解析电子邮件(来自,到,主题,附件等) 3.发送此电子邮件(将其再次放入本地后缀的队列中)

我做了1和2但是我遇到了第3个问题。

这就是我现在所拥有的:

package main 

import (
  "fmt"
  "github.com/jhillyerd/go.enmime"
  //"github.com/sendgrid/sendgrid-go"
  "net/smtp"
  "github.com/jordan-wright/email"
  "os"
  "net/mail"
  "io/ioutil"
  "bytes"
  )

func main() {

  mail_stdin, err := ioutil.ReadAll(os.Stdin)
  if err != nil {
      return
  }

  // Convert type to io.Reader
  buf := bytes.NewBuffer(mail_stdin)

  msg, err := mail.ReadMessage(buf)
  if err != nil {
    return
  }

  mime, err := enmime.ParseMIMEBody(msg)
  if err != nil {
    return
  }

  # saving attachments
  for _, value := range mime.Attachments {
    fmt.Println(value.FileName())

    err := ioutil.WriteFile(value.FileName(), value.Content(), 0664)
    if err != nil {
      //panic(err)
      return
    }

  fmt.Printf("From: %v\n", msg.Header.Get("From"))
  fmt.Printf("Subject: %v\n", mime.GetHeader("Subject"))
  fmt.Printf("Text Body: %v chars\n", len(mime.Text))
  fmt.Printf("HTML Body: %v chars\n", len(mime.Html))
  fmt.Printf("Inlines: %v\n", len(mime.Inlines))
  fmt.Printf("Attachments: %v\n", len(mime.Attachments))
  fmt.Println(mime.Attachments)
  fmt.Println(mime.OtherParts)
  fmt.Printf("Attachments: %v\n", mime.Attachments)
}

我已经使用:net / smtp,sendgrid-go和jordan-wright / email进行了一些测试。 我想做的就是再次从服务器向队列发送电子邮件(不做任何更改)。大多数这些模块需要有Auth,但我只是想简单地发送使用sendmail,就像我从bash那样做:

# echo "test" | mail {address}

1 个答案:

答案 0 :(得分:0)

使用net/smtp你可以相当容易地做到这一点...假设你有一个运行的smtp服务器,你可以连接到没有身份验证。我猜你想要实现的目标通过简单的gmail(https://www.digitalocean.com/community/tutorials/how-to-use-google-s-smtp-server)实现起来要容易得多(http://play.golang.org/p/ATDCgJGKZ3

无论如何,这里有几个代码示例来涵盖这两种情况;

    c, err := smtp.Dial("mail.example.com:25")
    if err != nil {
        log.Fatal(err)
    }
    defer c.Close()
    // Set the sender and recipient.
    c.Mail("sender@example.org")
    c.Rcpt("recipient@example.net")
    // Send the email body.
    wc, err := c.Data()
    if err != nil {
        log.Fatal(err)
    }
    defer wc.Close()
    buf := bytes.NewBufferString("This is the email body.")
    if _, err = buf.WriteTo(wc); err != nil {
        log.Fatal(err)
    }

或者这里是一个使用简单身份验证的游乐场示例; https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html除非您已经在您的开发箱上运行了一个smtp服务器,否则可能会更容易。