Go语言邮件群发器 main.go
// Multi-SendEmail project main.go
package main
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.com"
password := "密码"
host := "smtp.qq.com:25" //QQ为例
subject := "邮件标题"
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!")
}
}
}
使用说明:
编译出exe文件,把要发送的邮箱一行一个放入send.txt中,邮件内容放入email.txt中(HTML格式),运行。
这代码我也有在用,有很多不灵活的地方,仅供参考。
注意:注意端口号到底是哪个哦。