简单三步,用 Python 发邮件

'utf-8')#附件设置内容类型,方便起见,设置为二进制流part2['Content-Type'] = 'application/octet-stream'#设置附件头,添加文件名part2['Content-Disposition'] = 'attachment;filename="abc.txt"'#添加照片附件with open('1.png','rb')as fp: picture = MIMEImage(fp.read()) #与txt文件设置相似 picture['Content-Type'] = 'application/octet-stream' picture['Content-Disposition'] = 'attachment;filename="1.png"'#将内容附加到邮件主体中message.attach(part1)message.attach(part2)message.attach(picture)#登录并发送try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host,25) smtpObj.login(mail_user,mail_pass) smtpObj.sendmail( sender,receivers,message.as_string()) print('success') smtpObj.quit()except smtplib.SMTPException as e: print('error',e)

6.小结

通过上面的代码,想必大家已经对发邮件有了基本的认识。

从整体上我们要把握整个过程的思路:

  1. 登录

  2. 写邮件

  3. 发送

微观上我们需要了解: