python发送带附件的邮件

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
# content 邮件正文
def send_mail(content):

    sender = "发件人的邮箱地址"
    username = "发件人用户名"
    password = "发件人密码"
    subject = "邮件的标题"
    receiver = "收件人邮箱地址,多个用英文逗号隔开" eg: receiver=['[email protected]','[email protected]']
    filename ="附件的名字"
    smtpserver ="邮件服务地址如:" # smtp.exmail.qq.com

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['Subject'] = subject.decode('utf8').encode('gb2312')
    msg['To'] = COMMASPACE.join(receiver)  # COMMASPACE==', '
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(content.decode('utf8').encode('gb2312'), 'html', 'gb2312'))

    # 邮件附件
    attach = MIMEText(content.decode('utf8').encode('gbk'), 'html', 'gb2312')
    attach["Content-Type"] = 'application/octet-stream'
    attach["Content-Disposition"] = 'attachment; filename="' + filename.decode('utf8').encode(
        'gbk') + '.xls"'  # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    msg.attach(attach)

    smtp = smtplib.SMTP(smtpserver, 25)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

需开启发件人邮箱的IMAP/SMTP服务

你可能感兴趣的:(python)