请教高手:go 群发邮件问题

liuzhe · 2015-01-04 07:46:46 · 2643 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2015-01-04 07:46:46 的主题,其中的信息可能已经有所发展或是发生改变。

附上代码:

import (
    "bufio"
    "errors"
    "fmt"
    "io"
    "io/ioutil"
    "net/smtp"
    "os"
    "strings"
    "time"
)

func SendMail(user, password, host, to, subject, body, mailtype string) error {
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    var content_type string
    if mailtype == "html" {
    content_type = "Content-Type: text/html;charset=UTF-8"
    } else {
    content_type = "Content-Type: text/plain;charset=UTF-8"
    }
    msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}


func readLine2Array(filename string) ([]string, error) {
    result := make([]string, 0)
    file, err := os.Open(filename)
    if err != nil {
    return result, errors.New("Open file failed.")
    }
    defer file.Close()
    bf := bufio.NewReader(file)
    for {
    line, isPrefix, err1 := bf.ReadLine()
    if err1 != nil {
        if err1 != io.EOF {
        return result, errors.New("ReadLine no finish")
        }
        break
    }
    if isPrefix {
        return result, errors.New("Line is too long")
    }
    str := string(line)
    result = append(result, str)
    }
    return result, nil
}


func main() {
    fmt.Println("start...")
    user := "qq@qq.com"
    password := "密码"
    host := "smtp.qq.com:25"   //QQ为例
    subject := "使用Golang发送邮件"

    sendTo, err := readLine2Array("send.txt")
    if err != nil {
    fmt.Println(err)
    return
    }

    content, err := ioutil.ReadFile("email.txt")
    if err != nil {
    fmt.Println(err)
    return
    }
    body := string(content)

    for i := 0; i < len(sendTo); i++ {
    to := sendTo[i]
    fmt.Println("Send email to " + to)
    err = SendMail(user, password, host, to, subject, body, "html")
    if err != nil {
        fmt.Println("send mail error!")
        fmt.Println(err)
        i--
        time.Sleep(600 * time.Second)
    } else {
        fmt.Println("send mail success!")
    }
    }
}

在email.txt、send.txt分别写的是邮件内容和很多邮件地址 报出这样的错误:

main.go:1:1 expected 'package', found 'import'
main.go:2:5 expected ';' found 'STRING' "bufio"

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2643 次点击  
加入收藏 微博
2 回复  |  直到 2015-01-05 01:30:24
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传