【基础】练习册48-Python3_发送邮件:带附件和正文

2021-02-14  本文已影响0人  Alyna_C

代码如下:

#coding=utf-8

#发送邮件:带附件和正文

import smtplib

from email.mime.text import MIMEText

#from email.header import Header

from email.mime.multipart import MIMEMultipart

import os,time

sender = 'alyna_cai@163.com' #发送邮箱

receiver = '1755897460@qq.com' #接收邮箱

smtpserver = 'smtp.163.com' #发送邮箱服务器

pswd ='XCMQESJMOKLWRYBF' #开启stmp的授权码

msg = MIMEMultipart() #创建一个带附件的实例

msg['Subject'] = 'Python3测试邮件'#发送邮件主题

msg['From'] = sender

msg['To'] = receiver

msg.attach(MIMEText('这是python3 邮件发送测试......','plain','utf-8'))#邮件正文内容

#构造附件att,传送目录下的text.txt文件

#单附件发送

att = MIMEText(open('D:\\text.txt','rb').read(),'base64','utf-8')

att['Content-Type'] = 'application/octet-stream'

att['Content-Disposition'] = 'attachment;filename="text.txt"'

msg.attach(att)

'''

#多附件发送

#files = ['text.txt','text - 副本.txt']

#path = 'D:'

files = ['2.jpg','个人-娱乐爱好-电脑桌面.rar']

path = 'D:\\04-个人备份\\个人-娱乐爱好-电脑桌面'

for f in files:

    if os.path.isfile(path+'\\'+f):

        att = MIMEText(open(path+'\\'+f,'rb').read(),'base64','utf-8')

        att['Content-Type'] = 'application/octet-stream'

        att.add_header("Content-Disposition", "attachment", filename=("gbk", "", f))

    msg.attach(att)'''

try:

    '''

    #========登录第三方smtp邮箱发送邮件,支持25和465端口========

    #smtp port 25

    stmp = smtplib.SMTP(smtpserver,25) #smtp port 25

    stmp.login(sender,pswd) #使用授权码登录

    stmp.sendmail(sender,receiver,msg.as_string()) #发送邮件

    stmp.quit()

    print('send success by port 25')

    #smtp ssl port 465

    stmp = smtplib.SMTP_SSL(smtpserver,465)  #SMTP_SSL

    stmp.login(sender,pswd) #使用授权码登录

    stmp.sendmail(sender,receiver,msg.as_string()) #发送邮件

    stmp.quit()

    print('send success by port 465')'''

    #====================登录smtp服务器======================

    stmp = smtplib.SMTP()

    stmp.connect(smtpserver)

    stmp.login(sender,pswd) #使用授权码登录

    stmp.sendmail(sender,receiver,msg.as_string()) #发送邮件

    stmp.quit()

    print('send success') 

except smtplib.SMTPException:

    print("Error:无法发送邮件")

上一篇下一篇

猜你喜欢

热点阅读