1.使用yagmail
import yagmail #链接邮箱服务器 yag = yagmail.SMTP( user="user@126.com", password="1234", host='smtp.126.com') # 邮箱正文 contents = ['This is the body, and here is just text http://somedomain/image.png', 'You can find an audio file attached.', '/local/path/song.mp3'] # 发送邮件 yag.send('taaa@126.com', 'subject', contents) # 给多个用户发送 yag.send(['aa@126.com','bb@qq.com','cc@gmail.com'], 'subject', contents) # 发送带附件的邮件 yag.send('aaaa@126.com', '发送附件', contents, ["d://log.txt","d://baidu_img.jpg"])
2.使用email
from email.mime.text import MIMEText from email.header import Header import smtplib import getpass def send_mail(text, sender, receivers, subject, host, passwd): # 准备邮件 message = MIMEText(text, 'plain', 'utf8') message['From'] = Header(sender, 'utf8') message['To'] = Header(receivers[0], 'utf8') message['Subject'] = Header(subject, 'utf8') # 发送邮件 smtp = smtplib.SMTP() smtp.connect(host) smtp.login(sender, passwd) smtp.sendmail(sender, receivers, message.as_bytes()) if __name__ == '__main__': sender = 'raygift@163.com' receivers = ['752958210@qq.com'] subject = 'python邮件测试' text = '这是一封邮件测试。收到不用回复 ' host = 'smtp.136.com' passwd = getpass.getpass() send_mail(text, sender,receivers, subject, host, passwd)