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

来源:互联网 发布:python 定义类 编辑:程序博客网 时间:2024/06/05 15:27

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 smtplibimport email.mime.multipartimport email.mime.textfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplicationdef 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', 'fish@xxx.com.cn', '123456', 'fish@xxx.com.cn', subject, content)except Exception as err:    print(err)
原创粉丝点击