附上代码:
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"
有疑问加站长微信联系(非本文作者)