python 3.5上实现发送纯文本邮件

学python要慎重,真的,因为业界很多的书用的语句都是python 2.7。对于我这种无论在windows还是linux上都是安装3.5的忠实用户,看书不难操作难,因为好多的句法要现反应。


python 2.7和python 3.5上发送邮件是不同的,在python 3.5上实现发送邮件的语句是这样的:

#!/usr/bin/env python        #python环境地址
import smtplib          #加载电邮模块smtplib
import email.mime.multipart      #加载multipart
import email.mime.text         #加载mime.text,即纯文本 
      
msg=email.mime.multipart.MIMEMultipart()  
msg['from']='[email protected]'      #发送端地址
msg['to']='[email protected]'          #接受端地址
msg['subject']='这是一个python发送的纯文本邮件'      #邮件的标题
content="""                    
        妈妈:
         厨房里的菜刀我拿走了,不要问我去哪里,这个世界需要我!
            我是天神
    """                    #以上是邮件的内容
txt=email.mime.text.MIMEText(content)  
msg.attach(txt)  
      
smtp=smtplib  
smtp=smtplib.SMTP()              #创建一个SMTP对象
smtp.connect('smtp.sina.com','25')      #使用connect方法链接到新浪邮件服务器的25号端口
smtp.login('[email protected]','对应的邮箱密码')      #登入发送端需要账号验证
smtp.sendmail('[email protected]','[email protected]',str(msg))      #这句话才是邮件发送,括号内的顺序是(发送端,接收端,文件内容)
smtp.quit()                  #断开smtp链接

:wq 保存之后,#python  了它,邮箱那边的显示就是成功的。

51cto昨天下午上传本地图片屡次出现“网络链接有误”,不知道什么原因,所以图片欠奉。


还有一种写法,思路比较简单直白,而且无论是3.5还是2.7都可以启动,而且最重要的是,这个脚本里从头到尾都不用输入密码!如下图。

#!/usr/bin/env python

import smtplib

sender = '[email protected]'
receiver = ['[email protected]']        #接收方不可以是网易邮箱,会被吃掉

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
if you see this e-mail,that means you were successful.
"""

smtpObj = smtplib.SMTP('localhost')    #这里一定要有localhost
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email"
smtpObj.quit()
#except SMTPException:            #这个语句在python 2.7里不识别,但是在3.5里识别
#   print "Error: unable to send email"



 

http://www.runoob.com/python/python-email.html      

你可能感兴趣的:(linux,windows,用户)