举例详解Python中smtplib模块处理电子邮件的使用(2)

看上面的解释可能会觉得云里雾里,其实我对smtp, MIME的理解也很肤浅。但在大多数时候,我们只要会用就可以了。下面是一个简单的例子来演示如何使用这些类来发送带附件的邮件:
 

#coding=gbk import smtplib, mimetypes from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage msg = MIMEMultipart() msg['From'] = "from@yeah.net" msg['To'] = 'to@21cn.com' msg['Subject'] = 'email for tesing' #添加邮件内容 txt = MIMEText("这是邮件内容~~") msg.attach(txt) #添加二进制附件 fileName = r'e:/PyQt4.rar' ctype, encoding = mimetypes.guess_type(fileName) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('https://www.jb51.net/', 1) att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype) att1.add_header('Content-Disposition', 'attachment', filename = fileName) msg.attach(att1) #发送邮件 smtp = smtplib.SMTP() smtp.connect('smtp.yeah.net:25') smtp.login('from', '密码') smtp.sendmail('from@yeah.net', 'to@21cn.com', msg.as_string()) smtp.quit() print '邮件发送成功'

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdfyj.html