标签:服务器 nec chm 连接服务器 join users imp 理解 receive
email
两个模块,email
负责构造邮件,smtplib
负责发送邮件。注意到构造MIMETEXT对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入‘plain‘表示纯文本,最终的MIME就是‘text/plain’,最后一定要用utf-8编码保证多语言兼容性。
然后,通过SMTP发出去:
1 # coding:utf-8 2 import smtplib 3 from email.mime.text import MIMEText 4 5 6 class SendMail: 7 8 def send_mail(self, receiver_list, sub, content): 9 host = "smtp.qq.com" # 服务器地址 10 sender = "123@qq.com" # 发件地址 11 password = "pwd" 12 #邮件内容 13 message = MIMEText(content, _subtype=‘plain‘, _charset=‘utf-8‘) 14 message[‘Subject‘] = sub # 邮件主题 15 message[‘From‘] = sender 16 message[‘To‘] = ";".join(receiver_list) # 收件人之间以;分割 17 server = smtplib.SMTP() 18 # 连接服务器 19 server.connect(host=host) 20 # 登录 21 server.login(user=sender, password=password) 22 server.sendmail(from_addr=sender, to_addrs=receiver_list, msg=message.as_string()) 23 server.close() 24 25 if __name__ == ‘__main__‘: 26 send = SendMail() 27 receive = ["123qq.com", "456@163.com"] 28 sub = "测试邮件" 29 content = "测试邮件" 30 send.send_mail(receive, sub, content)
其实,这段代码也并不复杂,只要你理解使用过邮箱发送邮件,那么以下问题是你必须要考虑的:
首先需要安装库: pip install yagmail
然后:
1 import yagmail 2 3 4 class SendMail: 5 6 def send_mail(self, receiver_list, sub, content, attach=None): 7 host = "smtp.qq.com" 8 sender = "282410983@qq.com" 9 password = "ryprfozwyqawbgfg" 10 # 连接服务器 11 yag = yagmail.SMTP(user=sender, password=password, host=host) 12 # 邮件内容 13 yag.send(to=receiver_list, subject=sub, contents=content, attachments=attach) 14 15 16 if __name__ == ‘__main__‘: 17 send = SendMail() 18 receive = ["282410983@qq.com", "18850049513@163.com"] 19 sub = "测试邮件" 20 content = ["yagmail测试邮件", "\n", "hello word"] 21 attch = "C:\\Users\\Administrator\\Desktop\\10.jpg" 22 send.send_mail(receive, sub, content, attch)
另外,附件也可以之间写在content中,即conten = ["yagmail测试邮件", "\n", "hello word", "C:\\Users\\Administrator\\Desktop\\10.jpg"]
少写了好几行代码
标签:服务器 nec chm 连接服务器 join users imp 理解 receive
原文地址:https://www.cnblogs.com/dhs94/p/9886599.html