0%

python发送带附件的Gmail

QQ群:397745473

python发送带附件的Gmail

# 参考 https://techexpert.tips/zh-hans/python-zh-hans/python-%E4%BD%BF%E7%94%A8-gmail-%E5%8F%91%E9%80%81%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

username = "user@gmail.com"
password = "passwd"
mail_from = "user@gmail.com"
mail_to = "to@mail.com;"
mail_subject = "Test Subject"
mail_body = "This is a test message"
mail_attachment="1.png"
mail_attachment2="2.png"
mail_attachment_name="1.png"
mail_attachment_name2="2.png"

mimemsg = MIMEMultipart()
mimemsg['From']=mail_from
mimemsg['To']=mail_to
mimemsg['Subject']=mail_subject
mimemsg.attach(MIMEText(mail_body, 'plain'))

with open(mail_attachment, "rb") as attachment:
mimefile = MIMEBase('application', 'octet-stream')
mimefile.set_payload((attachment).read())
encoders.encode_base64(mimefile)
mimefile.add_header('Content-Disposition', "attachment; filename= %s" % mail_attachment_name)
mimemsg.attach(mimefile)

with open(mail_attachment2, "rb") as attachment:
mimefile = MIMEBase('application', 'octet-stream')
mimefile.set_payload((attachment).read())
encoders.encode_base64(mimefile)
mimefile.add_header('Content-Disposition', "attachment; filename= %s" % mail_attachment_name2)
mimemsg.attach(mimefile)

connection = smtplib.SMTP(host='smtp.gmail.com', port=587)
connection.starttls()
connection.login(username,password)
connection.send_message(mimemsg)
connection.quit()

QQ群:397745473

欢迎关注我的其它发布渠道