-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init4__.py
66 lines (57 loc) · 2.48 KB
/
__init4__.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 使用QQ邮箱发送附带附件的邮件
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
secretPass = 'brnhdxmvtqrwbeid' # SMTP服务器授权码
def send_email(sender_email, sender_pass, recipient_email, subject, message, attachment_paths):
# 创建邮件对象
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = recipient_email
# 添加附件正文
msg.attach(MIMEText(message, 'plain'))
# 添加邮件附件
for attachment_path in attachment_paths:
if attachment_path.endswith('.jpg'):
with open(attachment_path, 'rb') as attachment:
part = MIMEImage(attachment.read())
part.add_header('Content-Disposition', 'attachment', filename=attachment_path)
msg.attach(part)
elif attachment_path.endswith('.xlsx'):
with open(attachment_path, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=attachment_path)
msg.attach(part)
elif attachment_path.endswith('.txt'):
with open(attachment_path, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=attachment_path)
msg.attach(part)
with smtplib.SMTP_SSL('smtp.qq.com', 465) as smtp:
smtp.login(sender_email, sender_pass)
print('QQ邮箱——SMTP服务登录成功!')
smtp.send_message(msg)
print('邮件发送完毕')
smtp.quit() # 关闭SMTP连接
sender_email = '[email protected]' # 发信人邮箱
sender_pass = secretPass # 邮箱授权码
to_email = '[email protected]' # 收信人邮箱
sub_msg = '测试python发送邮件' # 邮件主题
content = '这是我的第一个python发送邮件测试' # 邮件正文内容
attachment_paths = [
'1.xlsx',
'1.jpg',
'emails.txt'
]
def main():
send_email(sender_email, sender_pass, to_email, sub_msg, content, attachment_paths) # 发送邮件
if __name__ == '__main__':
main()