Python 发送电子邮件

Python 发送电子邮件

Python 发送电子邮件需要依赖 smtplib 和 email 两个 Python 自带模块

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os

import time

def sent_mail(filename, filesrc, toaddr):
    msg = MIMEMultipart('related')
    fromaddr = os.environ.get('MAIL_ADREES')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'Sent' + os.path.basename(filename)

    # 邮件正文
    text = MIMEText('Thx for use DropKindle', 'plain', 'utf-8')
    msg.attach(text)

    # 邮件附件
    att = MIMEText(open(filesrc, 'rb').read(), 'base64', 'gbk')
    att["Content-Type"] = 'application/octet-stream'
    att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))
    msg.attach(att)
    smtp = smtplib.SMTP_SSL(os.environ.get('SMTP_SSL'))
    smtp.set_debuglevel(False)
    smtp.login(fromaddr, os.environ.get('MAIL_PASSWD'))
    smtp.sendmail(msg['From'], msg['To'], msg.as_string())
    smtp.quit()

start_time = time.time()
for i in range(20):
    sent_mail('test.txt', '/Users/allen/Project/CHF_Project/aha/text.txt', 'me@allen0125.com')
end_time = time.time()-start_time
print(end_time)

如果使用第三方模块 aiosmtplib 异步发送大量邮件的话可以大大提高发送效率

from email.utils import parseaddr, formataddr
from email.header import Header
import aiosmtplib
import logging

def _format_addr(s): #格式化地址 也方便发送中文
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


from_addr =
password = 
to_addr = 
smtp = aiosmtplib.SMTP(hostname='smtp.126.com', port=465,use_tls=True)
smtp.login(from_addr,password)

async def sendemail(to_addr, filesrc, filename):
    msg = MIMEMultipart('related')
    fromaddr =
    msg['From'] = fromaddr
    msg['To'] = to_addr
    msg['Subject'] = 'sent' + os.path.basename(filename)

    # 邮件正文
    text = MIMEText('Thx for use', 'plain', 'utf-8')
    msg.attach(text)

    # 邮件附件
    att = MIMEText(open(filesrc, 'rb').read(), 'base64', 'gbk')
    att["Content-Type"] = 'application/octet-stream'
    att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))
    msg.attach(att)
    try:
        await smtp.send_message(msg)
    except aiosmtplib.SMTPException as e:
        logging.error('sendemail:%s'%e)



myfun_list = (sendemail(to_addr, '/Users/text.txt', 'test.txt') for i in range(30))
print(myfun_list)
print(os.environ.get(os.environ.get('SMTP_SSL')))
start_time = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*myfun_list))
end_time = time.time()-start_time
print(end_time)