Python3.3 邮件发送 含附件(各种类型文件)

1、廖雪峰教程代码会出现此种错误:
smtplib.SMTPServerDisconnected: please run connect() first,弃用

2、TypeError: getsockaddrarg: AF_INET6 address must be tuple, not str
服务器地址类型设定为元组
3、UnicodeEncodeError: ‘utf-8’ codec can’t encode character ‘\udcc9’ in position 0: surrogates not allowed
有些采用读取附件内容然后再发送附件,读取附件中中文内容错误,utf-8 和 gbk均无效


可用程序代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_email(smtpHost, sendAddr, password, recipientAddrs, subject='', content=''):
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = sendAddr
    msg['to'] = recipientAddrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)


    # 添加附件,传送D:/软件/yasuo.rar文件
    part = MIMEApplication(open('D:/软件/yasuo.rar','rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="yasuo.rar")
    msg.attach(part)

    smtp = smtplib.SMTP()
    smtp.connect(smtpHost, '25')
    smtp.login(sendAddr, password)
    smtp.sendmail(sendAddr, recipientAddrs, str(msg))
    print("发送成功!")
    smtp.quit()

try:
    subject = 'Python 测试邮件'
    content = '这是一封来自 Python 编写的测试邮件。'
    send_email('xxsmtp.xxx.com.cn', '[email protected]', '123456', '[email protected]', subject, content)
except Exception as err:
    print(err)

你可能感兴趣的:(Python)