本文整理汇总了Golang中net/mail.ReadMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang ReadMessage函数的具体用法?Golang ReadMessage怎么用?Golang ReadMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ReadMessage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestEmailHeaders
func TestEmailHeaders(t *testing.T) {
var (
from = "[email protected]"
to = "[email protected]ple.com"
bcc = "[email protected]"
subject = "Test"
)
_, body, err := emailToMessages(&Email{
From: from,
To: []string{to},
Bcc: []string{bcc},
Subject: subject,
})
if err != nil {
t.Fatal(err)
}
r := bytes.NewBuffer(body)
m, err := mail.ReadMessage(r)
if err != nil {
t.Fatal(err)
}
if v := m.Header.Get("From"); v != from {
t.Fatalf("%s != %s", v, from)
}
if v := m.Header.Get("To"); v != to {
t.Fatalf("%s != %s", v, to)
}
if v := m.Header.Get("Bcc"); v != "" {
t.Fatalf("%s != \"\"", v)
}
if v := m.Header.Get("Subject"); v != subject {
t.Fatalf("%s != %s", v, subject)
}
}
示例2: testInlineAgainstStdLib
func testInlineAgainstStdLib(t *testing.T, msg *Message, rawBytes []byte) {
// confirm stdlib can parse it too
stdlibMsg, err := mail.ReadMessage(bytes.NewReader(rawBytes))
if err != nil {
t.Fatal("Standard Library could not parse message:", err)
}
// confirm stdlib headers match our headers
// StandardLibrary is not decoding Q-encoded headers. TODO: Re-enable when GoLang does this.
//if !reflect.DeepEqual(map[string][]string(msg.Header), map[string][]string(stdlibMsg.Header)) {
// t.Fatal("Message does not match its parsed counterpart")
//}
// confirm subsequent parts match
mixedReader := multipart.NewReader(stdlibMsg.Body, boundary(map[string][]string(stdlibMsg.Header)))
alternativePart, err := mixedReader.NextPart()
if err != nil {
t.Fatal("Couldn't get next part", err)
}
// test the multipart/alternative
testMultipartInlineWithStdLib(t, msg.Parts[0], alternativePart)
// test attachments
attachmentPart, err := mixedReader.NextPart()
if err != nil {
t.Fatal("Couldn't get next part", err)
}
testBodyPartWithStdLib(t, msg.Parts[1], attachmentPart)
// confirm EOF
if _, err = mixedReader.NextPart(); err != io.EOF {
t.Fatal("Should be EOF", err)
}
}
示例3: prepTemplate
func prepTemplate(parent *template.Template, fn, base string) error {
t := parent.New(base)
f, err := os.Open(fn)
if err != nil {
return err
}
defer f.Close()
msg, err := mail.ReadMessage(f)
if err != nil {
return err
}
for k, v := range defaultHeaders {
if msg.Header.Get(k) == "" {
msg.Header[k] = v
}
}
data := &bytes.Buffer{}
// This is the only place I could find this method. :/
http.Header(msg.Header).Write(data)
data.Write([]byte{'\r', '\n'})
_, err = io.Copy(data, msg.Body)
if err != nil {
return err
}
_, err = t.Parse(data.String())
return err
}
示例4: Get
// Get parses the email and returns all relevant data
func Get(con *data.Context, m io.Reader) (*Email, error) {
msg, err := mail.ReadMessage(m)
if err != nil {
return nil, fmt.Errorf("Error at mail.ReadMessage while parsing the email. Error: %v", err)
}
con.Log.Debugf("header: %v", msg.Header)
// get body
email, err := extract(con, msg.Header, msg.Body)
if err != nil {
return nil, fmt.Errorf("Error at extracting email. Error: %v", err)
}
//con.Log.Debugf("Received mail: %v", email)
namespaces, err := getNamespaces(msg)
if err != nil {
return nil, fmt.Errorf("Error at parsing the receiver fields. Error: %v", err)
}
con.Log.Debugf("Detected namespaces: %v", namespaces)
email.Namespaces = namespaces
email.Subject, err = getSubject(msg)
if err != nil {
con.Log.Errorf("Could not decode subject. Error: %v", err)
email.Subject = ""
}
return email, nil
}
示例5: FetchMessages
func FetchMessages(c *imap.Client, uidSet *imap.SeqSet) (fetched []MsgData, err error) {
cmd, errF := c.UIDFetch(uidSet, "RFC822")
if errF != nil {
err = errF
return
}
for cmd.InProgress() {
errC := c.Recv(-1)
if errC != nil {
return
}
for _, rsp := range cmd.Data {
uid := imap.AsNumber(rsp.MessageInfo().Attrs["UID"])
mime := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822"])
msg, errR := mail.ReadMessage(bytes.NewReader(mime))
if errR != nil {
continue
}
if msg != nil {
msgdata := GetMessage(msg, uid)
fetched = append(fetched, msgdata)
}
}
cmd.Data = nil
}
return
}
示例6: ReceiveMail
// ReceiveMail will receive an e-mail and echo it back to the sender.
func ReceiveMail(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
m, err := mail.ReadMessage(r.Body)
if err != nil {
log.Errorf(ctx, "Failed reading a mail!")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = echoMailFunc.Call(ctx, m)
if err != nil {
log.Errorf(ctx, "Failed enqueing handler for a mail!")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(w, "OK")
// TODO(flowlo):
// 1. Check whether range m.Header.AddressList("From")
// fits a registered customer
// 2. Filter mail content for further e-mail addresses
// 3. Create a Fingerprint
// 4. Mail the Fingerprint URL to the other address
}
示例7: main
func main() {
rawMessage := `From: Feather <[email protected]>
To: [email protected], [email protected]
Subject: =?utf-8?B?5rWL6K+V5Y+R6YCB?=
Date: Fri, 21 May 2010 08:54:49 +0800
Message-ID: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: plain
Hello Golang Mail`
buf := bytes.NewBuffer([]byte(rawMessage))
// parse mail message, buf may from net or somewhere.
msg, err := mail.ReadMessage(buf)
if err != nil {
panic(err)
}
// mail body
body, _ := ioutil.ReadAll(msg.Body)
fmt.Printf("Mail Body:\n%s\n", body)
fmt.Println("To Addresses:")
printAddrs(msg, "to")
fmt.Println("From Address:")
printAddrs(msg, "From")
// auto convert to golang time.Time
date, _ := msg.Header.Date()
fmt.Println("Date:", date)
// mime header will ignore case
fmt.Println("mime version:", msg.Header.Get("mime-version"))
}
示例8: SaveMail
func SaveMail(newmail chan *ServerMessage) {
for {
message := <-newmail
parsedMessage, err := mail.ReadMessage(strings.NewReader(message.Body.String()))
fmt.Println(parsedMessage, err)
}
}
示例9: main
func main() {
file, _ := os.Open("/Users/rbd/Temp/7ccaa5be-acf7-45c7-a289-c6bd2cb0492a.eml")
msg, _ := mail.ReadMessage(file) // Read email using Go's net/mail
mime, _ := enmime.ParseMIMEBody(msg) // Parse message body with enmime
// Headers are in the net/mail Message
fmt.Printf("From: %v\n", msg.Header.Get("From"))
fmt.Printf("From: %v\n", mime.GetHeader("From"))
// enmime can decode quoted-printable headers
fmt.Printf("Subject: %v\n", mime.GetHeader("Subject"))
// The plain text body is available as mime.Text
fmt.Printf("Text Body: %v chars\n", len(mime.Text))
fmt.Printf("Text Body: %s\n", mime.Text)
// The HTML body is stored in mime.Html
fmt.Printf("HTML Body: %v chars\n", len(mime.Html))
// mime.Inlines is a slice of inlined attacments
fmt.Printf("Inlines: %v\n", len(mime.Inlines))
// mime.Attachments contains the non-inline attachments
fmt.Printf("Attachments: %v\n", len(mime.Attachments))
}
示例10: UnpackMessage
func UnpackMessage(eml string, errors chan error, wg *sync.WaitGroup) {
if wg != nil {
defer wg.Done()
}
f, err := os.Open(eml)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening the %q message file for unpacking: %s",
eml,
err.Error()))
return
}
defer f.Close()
msg, err := mail.ReadMessage(f)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening the %q message file for unpacking: %s",
eml,
err.Error()))
return
}
partsIterate(msg.Header, msg.Body, cutExt(eml), errors)
}
示例11: HandleMail
func HandleMail(client_data string, client_rcpt_to string, gConfig map[string]string) {
var to = client_rcpt_to[1 : len(client_rcpt_to)-1]
addresses := strings.Split(to, ",")
for _, address := range addresses {
emailData := client_data[:len(client_data)-4]
msg, err := mail.ReadMessage(bytes.NewBuffer([]byte(emailData)))
if err != nil {
sendErrorReport(err, emailData, address, gConfig)
return
}
headers := make(map[string]string)
for key, value := range msg.Header {
headers[key] = value[0]
}
body, _ := ioutil.ReadAll(msg.Body)
encryptedBody := encrypt(string(body), address, gConfig)
sendEmail(headers, encryptedBody, address, gConfig)
}
}
示例12: main
func main() {
flag.Parse()
if filename == nil || strings.TrimSpace(*filename) == "" {
log.Fatal("--file is required")
}
fh, err := os.Open(*filename)
if err != nil {
log.Fatal(err)
}
msg, err := mail.ReadMessage(fh)
if err != nil {
log.Fatal(err)
}
m, err := mime.ParseMIMEBody(msg)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stderr, "HTML=%d Text=%d\n", len(m.HTML), len(m.Text))
if len(m.HTML) <= 0 {
log.Fatalf("No HTML part found in %s\n", *filename)
}
w := bufio.NewWriter(os.Stdout)
n, err := w.WriteString(m.HTML)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stderr, "Wrote %d bytes to standard output\n", n)
w.Flush()
}
示例13: fetchAllHeaders
func fetchAllHeaders(user, authToken, box string) ([]mail.Header, error) {
c, err := imap.DialTLS("imap.gmail.com:993", nil)
if err != nil {
return nil, err
}
_, err = c.Auth(oauthSASL{user, authToken})
if err != nil {
return nil, err
}
c.Select(box, true)
set, _ := imap.NewSeqSet("1:*")
cmd, err := imap.Wait(c.Fetch(set, "BODY.PEEK[HEADER.FIELDS (DATE)]"))
if err != nil {
return nil, err
}
headers := make([]mail.Header, 0, len(cmd.Data))
parseFailures := 0
for _, rsp := range cmd.Data {
header := imap.AsBytes(rsp.MessageInfo().Attrs["BODY[HEADER.FIELDS (DATE)]"]) // no peek
if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
headers = append(headers, msg.Header)
} else {
parseFailures++
}
}
log.Printf("Finished processing %d emails with %d parse failures.\n", len(headers), parseFailures)
return headers, nil
}
示例14: LoadMessage
func LoadMessage(path string) (*Message, error) {
m := &Message{path: path}
f, err := os.Open(path)
if err != nil {
return nil, err
}
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
defer f.Close()
msg, err := mail.ReadMessage(f)
if err != nil {
return nil, err
}
m.From = mimedec(msg.Header.Get("From"))
m.ReplyTo = mimedec(msg.Header.Get("reply-to"))
m.CCs = mimedec(msg.Header.Get("cc"))
m.To = mimedec(msg.Header.Get("To"))
m.Subject = mimedec(msg.Header.Get("Subject"))
m.Date, _ = msg.Header.Date()
m.size = fi.Size()
i := strings.LastIndex(path, ":2,")
if i != -1 {
m.Flags = parseFlags(path[i+3:])
}
return m, nil
}
示例15: TestMessage
func TestMessage(t *testing.T) {
msg := &Message{}
msg.SetFrom("Marc Weistroff", "[email protected]")
msg.AddTo("Marc Weistroff", "[email protected]")
msg.AddTo("Foo Bar", "[email protected]")
msg.AddCc("Bar Foo", "[email protected]")
msg.AddBcc("The Boss", "[email protected]")
msg.Subject = "Lorem ipsum gollum"
msg.Body = `Oy Mate!
Wanna drink a beer tonight?
Cheers`
proof, _ := mail.ReadMessage(bytes.NewBuffer(msg.Bytes()))
body, _ := ioutil.ReadAll(proof.Body)
if string(body) != msg.Body {
t.Log(string(body))
t.FailNow()
}
from, _ := proof.Header.AddressList("From")
if from[0].Name != "Marc Weistroff" || from[0].Address != "[email protected]" {
t.Log(from[0])
t.FailNow()
}
to, _ := proof.Header.AddressList("To")
if len(to) != 2 {
proof.Header.Get("To")
t.Log(to)
t.FailNow()
}
if to[0].Name != "Marc Weistroff" || to[0].Address != "[email protected]" {
t.Log(to[0])
t.FailNow()
}
if to[1].Name != "Foo Bar" || to[1].Address != "[email protected]" {
t.Log(to[1])
t.FailNow()
}
cc, _ := proof.Header.AddressList("Cc")
if cc[0].Name != "Bar Foo" || cc[0].Address != "[email protected]" {
t.Log(cc[0])
t.FailNow()
}
bcc, _ := proof.Header.AddressList("Bcc")
if bcc[0].Name != "The Boss" || bcc[0].Address != "[email protected]" {
t.Log(bcc[0])
t.FailNow()
}
subject := proof.Header.Get("Subject")
if subject != msg.Subject {
t.Log(subject)
t.FailNow()
}
}