-
例
# -*- coding: utf-8 -*-
"""
发送
"""
import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
now = lambda : time.perf_counter()
def main():
server = 'smtp.office365.com'
from_ = 'from@163.com'
pw = 'password'
to = 'example@163.com'
msg = MIMEMultipart() # 组合多个对象
msg['Subject'] = 'Python 测试'
msg['From'] = 'Fergus'
msg['To'] = to
#
body = '测试邮件'
msg.attach(MIMEText(body, 'plain', 'utf-8')) # MEMEText 文本对象
#
path = r'p.png'
if os.path.isfile(p):
with open(p, 'rb') as f:
png = MIMEApplication(f.read())
png.add_header('Content-Disposition', 'attachment', filename='附件1.png')
msg.attach(png)
else:
raise
with smtplib.SMTP(server, 25) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.set_debuglevel(1)
smtp.login(from_, pw)
try:
smtp.sendmail(from_, to, msg.as_string())
except:
print('失败')
else:
print("成功")
finally:
print('结束')
if __name__ == '__main__':
st = now()
main()
print(now() - st)