现在的位置: 首页 > 综合 > 正文

python发邮件

2018年03月15日 ⁄ 综合 ⁄ 共 2421字 ⁄ 字号 评论关闭

以前的公司上班上网或者收发邮件都得小心翼翼的,怕一不小心被有心人瞧见,又得被说说。为了能发邮件而不被发现,嘿嘿,我就用python写了个邮件发送程序,用控制台控制,不了解的人一定以为哥还在编程工作呢。哈哈。

        下面简单介绍下如何使用python发送邮件,包括普通文本内容,也可以带附件,或者HTML内容的邮件。可以说有了python,一切都变得非常的容易。

        smtplib 模块是用来发送email的标准module,另外配合email.mime内的几个module实现起来就非常的简单。

  1. def sendmail(message):  
  2.     try:  
  3.         smtp = smtplib.SMTP(EMAIL_HOST)  
  4.         smtp.login(EMAIL_USER, EMAIL_PWD)    
  5.         smtp.sendmail(EMAIL_USER+"@"+EMAIL_POSTFIX, TO_EMAIL, message)    
  6.         smtp.quit()    
  7.         print 'email send success.'  
  8.     except Exception ,e:  
  9.         print e  
  10.         print 'email send failed.'  

    首先要导入smtplib模块,加入import smtplib,初始化的时候直接连上邮箱服务器,也就是上面的EMAIL_HOST(我使用的是163邮箱,所以定义EMAIL_HOST = 'smtp.163.com'),由于目前的邮箱基本都需要登录才可以使用,所以要调用smtp.login()函数,输入用户和密码。

  1. def sendwithoutattachment():  
  2.     msg = MIMEText(getcontent(), 'plain','utf-8')  
  3.     getheader(msg)  
  4.       
  5.     sendmail(msg.as_string())  


    我将发送简单文本内容的邮件单独独立为一个函数,使用MIMEText生成,注意这里用到了utf-8,因为内容有可能是中文,所以要特别指定。如果要发送html内容,则讲plain更改为html即可。

  1. def getheader(msg):  
  2.     msg['From'] = ME  
  3.     msg['To'] = ";".join(TO_EMAIL)  
  4.     msg['Subject'] = EMAIL_HEADER  
  5.     msg['Date'] = formatdate(localtime=True)  


    getheader函数是用来设置发送者,接受者,主题和发送时间的。

  1. def getcontent():  
  2.     path = os.getcwd()  
  3.     file = os.path.join(path, CONTENT_FILE_NAME)  
  4.     content = open(file, 'rb')  
  5.     data = content.read()  
  6.     try:  
  7.         data = data.decode('gbk')  
  8.     except :  
  9.         data = data.decode('gbk','ignore')  
  10.     content.close()  
  11.     return data  

    至于邮件正文,我是事先写到一个TXT文档中,读取出来。这样也比较隐蔽。:)要主意中文编码。

  1. def getattachment(msg):  
  2.     ctype, encoding = mimetypes.guess_type(ACCESSORY_FULLPATH)  
  3.     if ctype is None or encoding is not None:    
  4.         ctype = 'application/octet-stream'    
  5.     maintype, subtype = ctype.split('/'1)  
  6.   
  7.     #Formating accessory data  
  8.     data = open(ACCESSORY_FULLPATH, 'rb')  
  9.     file_msg = MIMEBase(maintype, subtype)  
  10.     file_msg.set_payload(data.read( ))  
  11.     data.close( )  
  12.     encode_base64(file_msg)   
  13.     #file_msg["Content-Type"] = ctype # if add type then return error 10054  
  14.     file_msg.add_header('Content-Disposition''attachment', filename = ACCESSORY_NAME)  
  15.     msg.attach(file_msg)  

   附件同样独立为一个函数来创建,这里要注意的是不要指定“Content-Type”类型,否则无法发送邮件。这个问题还没有解决。

    以上基本包括了发送邮件的主要几个函数,具体smtplib模块和MIME等内容,资料很多,这里就不详细讲解了,有感兴趣的可以上网search。

抱歉!评论已关闭.