Golang:邮件发送
说明:感觉 github.com/go-gomail/gomail 这个包还不错,比较简洁,golang的代码案例是围绕着'gomail'写的,详细使用方法请去 github 查看,希望对你有帮助..."
代码:
安装方法:go get "github.com/go-gomail/gomail"
package main
import (
"fmt"
"github.com/go-gomail/gomail"
)
type Email struct {
Host string //服务器名
Port int //服务端口
From string //发件人
Pwd string //密码
To []string //收件人
Cc []string //抄送
Bcc []string //暗送
Subject string //主题
Body string //正文
AttachPath string //附件路径
}
func SendEmail(e *Email) {
m := gomail.NewMessage()
m.SetHeader("From", e.From) //发件人信息
m.SetHeader("To", e.To[0]) //收件人
//m.SetHeader("Cc", m.FormatAddress("xxxx@163.com", "")) //抄送
//m.SetHeader("Bcc", m.FormatAddress("xxxx@gmail.com", "")) //暗送
m.SetHeader("Subject", "测试脚本..") //主题
m.SetBody("text/html", e.Body) //正文
m.Attach(e.AttachPath) //附件
send := gomail.NewDialer(e.Host, e.Port, e.From, e.Pwd) // 发送邮件服务器、端口、发件人账号、发件人密码
if err := send.DialAndSend(m); err != nil {
fmt.Println("发送失败:", err)
return
}
fmt.Println("发送成功...")
}
func Sender() *Email {
return &Email{
Host: "smtp.xxxx.com", //服务器名
Port: 465, //端口
From: "发件人邮箱",
Pwd: "邮箱密码",
To: []string{"收件人邮箱"},
Subject: "测试...",
Body: "你好,正在测试...",
AttachPath: "附件路径",
}
}
func main() {
con := Sender()
SendEmail(con)
}
Python:邮件发送
代码:
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def create_email(f_name, e_send, e_recipient):
# 创建邮箱内容格式
message = MIMEMultipart()
message['Subject'] = '测试脚本' # 主题
message['From'] = e_send # 发送人
message['To'] = e_recipient # 接收人
# 内容文本部分
content = '你好,正在测试...' # 正文
e_con = MIMEText(content)
message.attach(e_con)
# 附件内容
file_path = 'D:/xxx/xxx/' + f_name # 文件路径
xlsx_cont = MIMEApplication(open(file_path, 'rb').read())
xlsx_cont.add_header('Content-Disposition', 'attachment', filename=f_name)
message.attach(xlsx_cont)
return message
def connect_email(e_server, e_send, e_pwd, e_recipient, message):
# 建立邮箱连接,发送信息
try:
server = smtplib.SMTP_SSL(e_server, 465)
server.login(e_send, e_pwd)
server.sendmail(e_send, [e_recipient], message.as_string())
print('邮件发送成功', time.strftime('%Y.%m.%d %H:%M:%S ', time.localtime(time.time())))
server.quit()
except Exception as e:
print('邮件发送失败,错误信息:%s...' % e)
if __name__ == '__main__':
email_server = 'smtp.xxx.com' # 邮箱服务地址
sender = 'xxxxx@163.com' # 发送者邮箱
sender_pwd = 'pwd' # 发送者邮箱密码
recipient = 'xxxxx@163.com' # 接收者邮箱
file_name = 'file.xlsx'
message_con = create_email(file_name, sender, recipient)
connect_email(email_server, sender, sender_pwd, recipient, message_con)