python 发送邮件

来源:互联网 发布:马来西亚第二家园 知乎 编辑:程序博客网 时间:2024/06/07 21:02

import smtplib, datetimefrom email.Header import Headerfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartmsg = MIMEMultipart()#attachmentatt = MIMEText(open('/home/temp/send_mail.py', 'rb').read(), 'base64', 'gb2312')att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = 'attachment; filename="send_mail.txt"'msg.attach(att)#contentmsg_content = MIMEText("hello, content", 'plain','utf-8')msg.attach(msg_content) msg['from'] = 'xxx@qq.com'#one reciever#msg['to'] = 'xxx@qq.com'#mutiple recievermsg['to'] = "xxx@qq.com,bbbb@qq.com"msg['subject'] = Header('test (' + str(datetime.date.today()) + ')','gb2312')server = smtplib.SMTP('smtp.qq.com')server.login('xxx@qq.com','xxxxx')error=server.sendmail(msg['from'], msg['to'],msg.as_string())server.closeprint error

ref:

1, http://blog.chinaunix.net/uid-21516619-id-1825025.html

# -*- coding: cp936 -*-
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import smtplib, datetime

#创建一个带附件的实例
msg = MIMEMultipart()

#构造附件
att = MIMEText(open('f:\\文件名.doc', 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="文件名.doc"'
msg.attach(att)

#加邮件头
msg['to'] = '137951467@qq.com'
msg['from'] = '137951467@qq.com'
msg['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')','gb2312')

#发送邮件
server = smtplib.SMTP('smtp.qq.com')
server.login('137951467','123456')
error=server.sendmail(msg['from'], msg['to'],msg.as_string())
server.close
print error

2,http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html

python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点。

    一、相关模块介绍

    发送邮件主要用到了smtplib和email两个模块,这里首先就两个模块进行一下简单的介绍:
    1、smtplib模块

      smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

   SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接可以向smtp服务器发送指令,执行相关操作(如:登陆、发送邮件)。所有参数都是可选的。

     host:smtp服务器主机名

     port:smtp服务的端口,默认是25;如果在创建SMTP对象的时候提供了这两个参数,在初始化的时候会自动调用connect方法去连接服务器。

   smtplib模块还提供了SMTP_SSL类和LMTP类,对它们的操作与SMTP基本一致。

  smtplib.SMTP提供的方法:

     SMTP.set_debuglevel(level):设置是否为调试模式。默认为False,即非调试模式,表示不输出任何调试信息。

     SMTP.connect([host[, port]]):连接到指定的smtp服务器。参数分别表示smpt主机和端口。注意: 也可以在host参数中指定端口号(如:smpt.yeah.net:25),这样就没必要给出port参数。

     SMTP.docmd(cmd[, argstring]):向smtp服务器发送指令。可选参数argstring表示指令的参数。

     SMTP.helo([hostname]) :使用"helo"指令向服务器确认身份。相当于告诉smtp服务器“我是谁”。

     SMTP.has_extn(name):判断指定名称在服务器邮件列表中是否存在。出于安全考虑,smtp服务器往往屏蔽了该指令。

     SMTP.verify(address) :判断指定邮件地址是否在服务器中存在。出于安全考虑,smtp服务器往往屏蔽了该指令。

     SMTP.login(user, password) :登陆到smtp服务器。现在几乎所有的smtp服务器,都必须在验证用户信息合法之后才允许发送邮件。

     SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。

     SMTP.quit() :断开与smtp服务器的连接,相当于发送"quit"指令。(很多程序中都用到了smtp.close(),具体与quit的区别google了一下,也没找到答案。)

     2、email模块

     emial模块用来处理邮件消息,包括MIME和其他基于RFC 2822 的消息文档。使用这些模块来定义邮件的内容,是非常简单的。其包括的类有(更加详细的介绍可见:http://docs.python.org/library/email.mime.html):

    class email.mime.base.MIMEBase(_maintype, _subtype, **_params):这是MIME的一个基类。一般不需要在使用时创建实例。其中_maintype是内容类型,如text或者image。_subtype是内容的minor type 类型,如plain或者gif。 **_params是一个字典,直接传递给Message.add_header()。

    class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:MIMEBase的一个子类,多个MIME对象的集合,_subtype默认值为mixed。boundary是MIMEMultipart的边界,默认边界是可数的。

    class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一个子类。

    class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音频对象

    class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二进制文件对象。

    class email.mime.message.MIMEMessage(_msg[, _subtype]):具体的一个message实例,使用方法如下:

   

msg=mail.Message.Message()    #一个实例 
msg['to']='XXX@XXX.com' #发送到哪里
msg['from']='YYY@YYYY.com' #自己的邮件地址
msg['date']='2012-3-16' #时间日期
msg['subject']='hello world' #邮件主题

 

    class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本对象,其中_text是邮件内容,_subtype邮件类型,可以是text/plain(普通文本邮件),html/plain(html邮件),  _charset编码,可以是gb2312等等。

    二、几种邮件的具体实现代码

    1、普通文本邮件

    普通文本邮件发送的实现,关键是要将MIMEText中_subtype设置为plain。首先导入smtplib和mimetext。创建smtplib.smtp实例,connect邮件smtp服务器,login后发送,具体代码如下:(python2.6下实现)

复制代码
# -*- coding: UTF-8 -*-
'''
发送txt文本邮件
小五义:http://www.cnblogs.com/xiaowuyi
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=[YYY@YYY.com]
mail_host="smtp.XXX.com" #设置服务器
mail_user="XXXX" #用户名
mail_pass="XXXXXX" #口令
mail_postfix="XXX.com" #发件箱的后缀

def send_mail(to_list,sub,content):
me="hello"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","hello world!"):
print "发送成功"
else:
print "发送失败"
复制代码

    2、html邮件的发送

    与text邮件不同之处就是将将MIMEText中_subtype设置为html。具体代码如下:(python2.6下实现)

复制代码
# -*- coding: utf-8 -*-
'''
发送html文本邮件
小五义:http://www.cnblogs.com/xiaowuyi
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=["YYY@YYY.com"]
mail_host="smtp.XXX.com" #设置服务器
mail_user="XXX" #用户名
mail_pass="XXXX" #口令
mail_postfix="XXX.com" #发件箱的后缀

def send_mail(to_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容
me="hello"+"<"+mail_user+"@"+mail_postfix+">" #这里的hello可以任意设置,收到信后,将按照设置显示
msg = MIMEText(content,_subtype='html',_charset='gb2312') #创建一个实例,这里设置为html格式邮件
msg['Subject'] = sub #设置主题
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host) #连接smtp服务器
s.login(mail_user,mail_pass) #登陆服务器
s.sendmail(me, to_list, msg.as_string()) #发送邮件
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五义</a>"):
print "发送成功"
else:
print "发送失败"

复制代码

   3、发送带附件的邮件

    发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。

复制代码
# -*- coding: cp936 -*-
'''
发送带附件邮件
小五义:http://www.cnblogs.com/xiaowuyi
'''

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#创建一个带附件的实例
msg = MIMEMultipart()

#构造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

#构造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)

#加邮件头
msg['to'] = 'YYY@YYY.com'
msg['from'] = 'XXX@XXX.com'
msg['subject'] = 'hello world'
#发送邮件
try:
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXX')#XXX为用户名,XXXXX为密码
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e)
复制代码

     4、利用MIMEimage发送图片

   

复制代码
# -*- coding: cp936 -*-
import smtplib
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def AutoSendMail():
msg = MIMEMultipart()
msg['From'] = "XXX@XXX.com"
msg['To'] = "YYY@YYY.com"
msg['Subject'] = "hello world"


txt = MIMEText("这是中文的邮件内容哦",'plain','gb2312')
msg.attach(txt)


file1 = "C:\\hello.jpg"
image = MIMEImage(open(file1,'rb').read())
image.add_header('Content-ID','<image1>')
msg.attach(image)


server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXXX')
server.sendmail(msg['From'],msg['To'],msg.as_string())
server.quit()

if __name__ == "__main__":
AutoSendMail()
复制代码

   

    利用MIMEimage发送图片,原本是想图片能够在正文中显示,可是代码运行后发现,依然是以附件形式发送的,希望有高手能够指点一下,如何可以发送在正文中显示的图片的邮件,就是图片是附件中存在,但同时能显示在正文中,具体形式如下图。


3,http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343463.html

文件形式的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5. from email.header import Header  
  6.   
  7. sender = '***'  
  8. receiver = '***'  
  9. subject = 'python email test'  
  10. smtpserver = 'smtp.163.com'  
  11. username = '***'  
  12. password = '***'  
  13.   
  14. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要  
  15. msg['Subject'] = Header(subject, 'utf-8')  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  

HTML形式的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5.   
  6. sender = '***'  
  7. receiver = '***'  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'  
  12.   
  13. msg = MIMEText('<html><h1>你好</h1></html>','html','utf-8')  
  14.   
  15. msg['Subject'] = subject  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  

带图片的HTML邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage  
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'  
  14.   
  15. msgRoot = MIMEMultipart('related')  
  16. msgRoot['Subject'] = 'test message'  
  17.   
  18. msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')  
  19. msgRoot.attach(msgText)  
  20.   
  21. fp = open('h:\\python\\1.jpg''rb')  
  22. msgImage = MIMEImage(fp.read())  
  23. fp.close()  
  24.   
  25. msgImage.add_header('Content-ID''<image1>')  
  26. msgRoot.attach(msgImage)  
  27.   
  28. smtp = smtplib.SMTP()  
  29. smtp.connect('smtp.163.com')  
  30. smtp.login(username, password)  
  31. smtp.sendmail(sender, receiver, msgRoot.as_string())  
  32. smtp.quit()  

带附件的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage  
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'  
  14.   
  15. msgRoot = MIMEMultipart('related')  
  16. msgRoot['Subject'] = 'test message'  
  17.   
  18. #构造附件  
  19. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
  20. att["Content-Type"] = 'application/octet-stream'  
  21. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
  22. msgRoot.attach(att)  
  23.           
  24. smtp = smtplib.SMTP()  
  25. smtp.connect('smtp.163.com')  
  26. smtp.login(username, password)  
  27. smtp.sendmail(sender, receiver, msgRoot.as_string())  
  28. smtp.quit()  

群邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5.   
  6. sender = '***'  
  7. receiver = ['***','****',……]  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'  
  12.   
  13. msg = MIMEText('你好','text','utf-8')  
  14.   
  15. msg['Subject'] = subject  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  

各种元素都包含的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage  
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'  
  14.   
  15. # Create message container - the correct MIME type is multipart/alternative.  
  16. msg = MIMEMultipart('alternative')  
  17. msg['Subject'] = "Link"  
  18.   
  19. # Create the body of the message (a plain-text and an HTML version).  
  20. text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"  
  21. html = """\ 
  22. <html> 
  23.   <head></head> 
  24.   <body> 
  25.     <p>Hi!<br> 
  26.        How are you?<br> 
  27.        Here is the <a href="http://www.python.org">link</a> you wanted. 
  28.     </p> 
  29.   </body> 
  30. </html> 
  31. """  
  32.   
  33. # Record the MIME types of both parts - text/plain and text/html.  
  34. part1 = MIMEText(text, 'plain')  
  35. part2 = MIMEText(html, 'html')  
  36.   
  37. # Attach parts into message container.  
  38. # According to RFC 2046, the last part of a multipart message, in this case  
  39. # the HTML message, is best and preferred.  
  40. msg.attach(part1)  
  41. msg.attach(part2)  
  42. #构造附件  
  43. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
  44. att["Content-Type"] = 'application/octet-stream'  
  45. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
  46. msg.attach(att)  
  47.      
  48. smtp = smtplib.SMTP()  
  49. smtp.connect('smtp.163.com')  
  50. smtp.login(username, password)  
  51. smtp.sendmail(sender, receiver, msg.as_string())  
  52. smtp.quit()  

基于SSL的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5. from email.header import Header  
  6. sender = '***'  
  7. receiver = '***'  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'  
  12.   
  13. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要  
  14. msg['Subject'] = Header(subject, 'utf-8')  
  15.   
  16. smtp = smtplib.SMTP()  
  17. smtp.connect('smtp.163.com')  
  18. smtp.ehlo()  
  19. smtp.starttls()  
  20. smtp.ehlo()  
  21. smtp.set_debuglevel(1)  
  22. smtp.login(username, password)  
  23. smtp.sendmail(sender, receiver, msg.as_string())  
  24. smtp.quit()  

    文件形式的邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.text import MIMEText  
    5. from email.header import Header  
    6.   
    7. sender = '***'  
    8. receiver = '***'  
    9. subject = 'python email test'  
    10. smtpserver = 'smtp.163.com'  
    11. username = '***'  
    12. password = '***'  
    13.   
    14. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要  
    15. msg['Subject'] = Header(subject, 'utf-8')  
    16.   
    17. smtp = smtplib.SMTP()  
    18. smtp.connect('smtp.163.com')  
    19. smtp.login(username, password)  
    20. smtp.sendmail(sender, receiver, msg.as_string())  
    21. smtp.quit()  

    HTML形式的邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.text import MIMEText  
    5.   
    6. sender = '***'  
    7. receiver = '***'  
    8. subject = 'python email test'  
    9. smtpserver = 'smtp.163.com'  
    10. username = '***'  
    11. password = '***'  
    12.   
    13. msg = MIMEText('<html><h1>你好</h1></html>','html','utf-8')  
    14.   
    15. msg['Subject'] = subject  
    16.   
    17. smtp = smtplib.SMTP()  
    18. smtp.connect('smtp.163.com')  
    19. smtp.login(username, password)  
    20. smtp.sendmail(sender, receiver, msg.as_string())  
    21. smtp.quit()  

    带图片的HTML邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.multipart import MIMEMultipart  
    5. from email.mime.text import MIMEText  
    6. from email.mime.image import MIMEImage  
    7.   
    8. sender = '***'  
    9. receiver = '***'  
    10. subject = 'python email test'  
    11. smtpserver = 'smtp.163.com'  
    12. username = '***'  
    13. password = '***'  
    14.   
    15. msgRoot = MIMEMultipart('related')  
    16. msgRoot['Subject'] = 'test message'  
    17.   
    18. msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')  
    19. msgRoot.attach(msgText)  
    20.   
    21. fp = open('h:\\python\\1.jpg''rb')  
    22. msgImage = MIMEImage(fp.read())  
    23. fp.close()  
    24.   
    25. msgImage.add_header('Content-ID''<image1>')  
    26. msgRoot.attach(msgImage)  
    27.   
    28. smtp = smtplib.SMTP()  
    29. smtp.connect('smtp.163.com')  
    30. smtp.login(username, password)  
    31. smtp.sendmail(sender, receiver, msgRoot.as_string())  
    32. smtp.quit()  
    带附件的邮件
    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.multipart import MIMEMultipart  
    5. from email.mime.text import MIMEText  
    6. from email.mime.image import MIMEImage  
    7.   
    8. sender = '***'  
    9. receiver = '***'  
    10. subject = 'python email test'  
    11. smtpserver = 'smtp.163.com'  
    12. username = '***'  
    13. password = '***'  
    14.   
    15. msgRoot = MIMEMultipart('related')  
    16. msgRoot['Subject'] = 'test message'  
    17.   
    18. #构造附件  
    19. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
    20. att["Content-Type"] = 'application/octet-stream'  
    21. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
    22. msgRoot.attach(att)  
    23.           
    24. smtp = smtplib.SMTP()  
    25. smtp.connect('smtp.163.com')  
    26. smtp.login(username, password)  
    27. smtp.sendmail(sender, receiver, msgRoot.as_string())  
    28. smtp.quit()  

    群邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.text import MIMEText  
    5.   
    6. sender = '***'  
    7. receiver = ['***','****',……]  
    8. subject = 'python email test'  
    9. smtpserver = 'smtp.163.com'  
    10. username = '***'  
    11. password = '***'  
    12.   
    13. msg = MIMEText('你好','text','utf-8')  
    14.   
    15. msg['Subject'] = subject  
    16.   
    17. smtp = smtplib.SMTP()  
    18. smtp.connect('smtp.163.com')  
    19. smtp.login(username, password)  
    20. smtp.sendmail(sender, receiver, msg.as_string())  
    21. smtp.quit()  

    各种元素都包含的邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.multipart import MIMEMultipart  
    5. from email.mime.text import MIMEText  
    6. from email.mime.image import MIMEImage  
    7.   
    8. sender = '***'  
    9. receiver = '***'  
    10. subject = 'python email test'  
    11. smtpserver = 'smtp.163.com'  
    12. username = '***'  
    13. password = '***'  
    14.   
    15. # Create message container - the correct MIME type is multipart/alternative.  
    16. msg = MIMEMultipart('alternative')  
    17. msg['Subject'] = "Link"  
    18.   
    19. # Create the body of the message (a plain-text and an HTML version).  
    20. text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"  
    21. html = """\ 
    22. <html> 
    23.   <head></head> 
    24.   <body> 
    25.     <p>Hi!<br> 
    26.        How are you?<br> 
    27.        Here is the <a href="http://www.python.org">link</a> you wanted. 
    28.     </p> 
    29.   </body> 
    30. </html> 
    31. """  
    32.   
    33. # Record the MIME types of both parts - text/plain and text/html.  
    34. part1 = MIMEText(text, 'plain')  
    35. part2 = MIMEText(html, 'html')  
    36.   
    37. # Attach parts into message container.  
    38. # According to RFC 2046, the last part of a multipart message, in this case  
    39. # the HTML message, is best and preferred.  
    40. msg.attach(part1)  
    41. msg.attach(part2)  
    42. #构造附件  
    43. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
    44. att["Content-Type"] = 'application/octet-stream'  
    45. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
    46. msg.attach(att)  
    47.      
    48. smtp = smtplib.SMTP()  
    49. smtp.connect('smtp.163.com')  
    50. smtp.login(username, password)  
    51. smtp.sendmail(sender, receiver, msg.as_string())  
    52. smtp.quit()  

    基于SSL的邮件

    1. #!/usr/bin/env python3  
    2. #coding: utf-8  
    3. import smtplib  
    4. from email.mime.text import MIMEText  
    5. from email.header import Header  
    6. sender = '***'  
    7. receiver = '***'  
    8. subject = 'python email test'  
    9. smtpserver = 'smtp.163.com'  
    10. username = '***'  
    11. password = '***'  
    12.   
    13. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要  
    14. msg['Subject'] = Header(subject, 'utf-8')  
    15.   
    16. smtp = smtplib.SMTP()  
    17. smtp.connect('smtp.163.com')  
    18. smtp.ehlo()  
    19. smtp.starttls()  
    20. smtp.ehlo()  
    21. smtp.set_debuglevel(1)  
    22. smtp.login(username, password)  
    23. smtp.sendmail(sender, receiver, msg.as_string())  
    24. smtp.quit()  
分类: python


0 0
原创粉丝点击