python 发送邮件

今天给大家介绍一下怎样利用python发送邮件。

情况一:发送纯文本邮件:

 1 #邮件发送库
 2 import smtplib
 3 #邮件的标题
 4 from email.header import Header
 5 #邮件的正文
 6 from email.mime.text import MIMEText
 7 
 8 def send_mail(user,pwd,sender,receiver,content,title):
 9 
10     #邮箱服务器主机名
11     mail_host = "smtp.163.com"
12     #创建邮件对象
13     message = MIMEText(content,"plain","utf-8")
14 
15     message["From"] = sender
16     message["To"] = ','.join(receiver)
17     message["Subject"] = title
18 
19     #启动ssl发送邮件
20     smtp_obj = smtplib.SMTP_SSL(mail_host,465)
21 
22     smtp_obj.login(user,pwd) #登录
23 
24     smtp_obj.sendmail(sender,receiver,message.as_string())
25 
26     print("发送成功!")
27 
28 if __name__ == "__main__":
29     user = "XXX" #用户名
30     pwd = "XXX"  #客户端授权码
31     sender = user
32     recevier = ["XXX","XXX"]  #抄送多个人
33 
34     content = "邮箱发送测试"
35     title = "邮箱发送"
36 
37     send_mail(user,pwd,sender,recevier,content,title)

方式二:发送带有附件的邮件

 1 import smtplib
 2 from email.mime.multipart import MIMEMultipart
 3 from email.mime.text import MIMEText
 4 from email.mime.application import MIMEApplication
 5 
 6 user = "XXX" #用户邮箱
 7 pwd = "XXX"  #客户端授权码
 8 
 9 sender = user
10 receiver = ",".join(["XXX"]) #接受方,抄送多人
11 
12 msg = MIMEMultipart()
13 msg["From"] = sender
14 msg["To"] = receiver
15 msg["Subject"] = "有附件的邮件..."
16 
17 text = MIMEText("正文部分")
18 msg.attach(text)  #添加文本内容
19 
20 pic_content = open("pic.jpg","rb").read()
21 application = MIMEApplication(pic_content)
22 application.add_header("Content-Disposition","attachment",filename='image.jpg')
23 msg.attach(application) #添加附件内容
24 
25 smtp_obj = smtplib.SMTP()
26 smtp_obj.connect("smtp.163.com")
27 smtp_obj.login(user,pwd)
28 smtp_obj.sendmail(sender,receiver,msg.as_string())
29 
30 smtp_obj.quit()

 

posted on 2019-10-10 22:58  心五口  阅读(442)  评论(0)    收藏  举报

导航