python发送邮件心得体会
2019-04-22 18:41 tangxiaosheng 阅读(1090) 评论(0) 编辑 收藏 举报利用本地smtp server发送
windows下尝试装了两个smtp server大概配置了下,发现没法生效,也没时间仔细研究了。装上foxmail发现以前可以本地发送的选项已经无法找到。
不带附件的这样发送。
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header sender = 'tangjian@tangjian.dell' # receivers = ['tangxiaosheng@yeah.net'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 receivers = ['jian.tang@zongmutech.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') # 发送者 message['To'] = Header("测试", 'utf-8') # 接收者 subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件"
利用smtp服务器发送
#!/usr/bin/python #coding: utf-8 import os import sys import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart def sendMail(receiver, subject, content, attachment=None): sender = 'tangxiaosheng@21cn.com' #定义邮件主题和正文 content ='<html><h1>' + content + '</h1></html>' #定义邮箱服务器和邮箱账户 smtpserver = 'smtp.21cn.com' username = 'tangxiaosheng@21cn.com' password = 'xxxx' #定义邮件三大主题 #如果一封邮件中含有附件,那邮件的Content-Type域中必须定义multipart/mixed类型 msgRoot = MIMEMultipart('mixed') msgRoot['Subject'] = subject msgRoot['From'] = sender msgRoot['To'] = receiver #构造邮件正文 msgText = MIMEText(content,'html','utf-8') msgRoot.attach(msgText) if attachment: fp = open(attachment, 'rb') baseName = os.path.basename(attachment) msgAtt = MIMEText(fp.read(),'base64','utf-8') msgAtt["Content-Type"] = 'application/octet-stream' msgAtt["Content-Disposition"] = 'attachment; filename=%s' % baseName msgRoot.attach(msgAtt) smtp = smtplib.SMTP() smtp.connect('smtp.21cn.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit() if __name__=='__main__': subject = '这是邮件主题' content = 'this mail has attachmet' # sendMail(subject, content, './mailatt.py') if len(sys.argv) >= 5:
sendMail(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
else:
sendMail(sys.argv[1], sys.argv[2], sys.argv[3])
#!/usr/bin/python 这一行要有。方便从命令行调用 mailatt.py .....,如果是 #!/usr/bin/evn python 更合适,适合多个python的版本。
用公司提供的邮箱发送时,碰到问题,修改后解决。原因不明。
msgRoot['To'] 一定需要是字符串类型的,不能是列表。
import os import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart def sendMail(): host = '192.168.5.10' # host = '42.159.161.202' sender = 'beitest_reporter@zongmutech.com' receiver = 'jian.tang@zongmutech.com' subject = '这是邮件主题' #定义邮件主题 content = u'这是邮件内容' # content = 'this is content' username = 'beitest_reporter' #定义登录邮箱账户 password = '' #定义登录邮箱密码 msg = MIMEText(content.encode('utf-8'),'plain','utf-8' ) #第二个参数使用'plain',如果使用'text'发送内容为空,不知道为什么 msg['From']=sender #一定要指定'From'属性,否则会报554 msg['To']=receiver #多个邮件接收人时,如果报错,可以不指定 msg['Subject'] = Header(subject, 'utf-8') try: smtp = smtplib.SMTP(host, 25) # smtp = smtplib.SMTP_SSL(host, 25) # print 'aaa' # smtp.set_debuglevel(True) # smtp.ehlo() # smtp.starttls() # smtp.ehlo() # status = smtp.login(username, password) # print status smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() except: print("邮件发送失败!") def sendmail1(): file = '/home/tangjian/work/analyze_python/data/result/report.html' print "mail_file = " + file receiver = 'jian.tang@zongmutech.com' sender = 'beitest_reporter@zongmutech.com' msgRoot = MIMEMultipart('mixed') msgRoot['Subject'] = "Test Report" msgRoot['From'] = sender msgRoot['To'] = receiver htmlfile = open(file) htmlbody = htmlfile.read() msgText = MIMEText(htmlbody,'html','utf-8') msgRoot.attach(msgText) fp = open(file, 'rb') msgAtt = MIMEText(fp.read(),'base64','utf-8') msgAtt["Content-Type"] = 'application/octet-stream' filename = os.path.basename(file) msgAtt["Content-Disposition"] = 'attachment; filename=%s' % filename msgRoot.attach(msgAtt) smtp = smtplib.SMTP('192.168.5.10') smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit() # SMTP AUTH extension not supported by server if __name__=='__main__': # sendMail() sendmail1()
两个函数都能work,先前第一个函数是用21cn做位smtp服务器可以work的代码。公司的服务器,没有密码。
content = u'这是邮件内容' #这一行前面对于中文要加 “u”。另外
msg = MIMEText(content.encode('utf-8') #加上encode(...)
尝试yeah发送的时候,
smtp = smtplib.SMTP(host, 25) # smtp = smtplib.SMTP_SSL(host, 25) # smtp.set_debuglevel(True) # smtp.ehlo() smtp.starttls() # smtp.ehlo() status = smtp.login(username, password) print 'status', status smtp.sendmail(sender, receiver, msg.as_string())
原先用smtplib.SMTP_SSL(host, 25),无论如何都不行。yahoo也是无论如何都不行,无论是用 SSL还是不用SSL。 比yeah还要差些。
Python中发邮件(明文/SSL/TLS三种方式)
#!/usr/bin/python # coding:utf-8 import smtplib from email.MIMEText import MIMEText from email.Utils import formatdate from email.Header import Header import sys #设置默认字符集为UTF8 不然有些时候转码会出问题 default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) #发送邮件的相关信息,根据你实际情况填写 smtpHost = 'smtp.126.com' smtpPort = '25' sslPort = '587' fromMail = 'zhangsan@126.com' toMail = 'funame@126.com' username = 'zhangsan' password = '123456' #邮件标题和内容 subject = u'[Notice]hello' body = u'hello,this is a mail from ' + fromMail #初始化邮件 encoding = 'utf-8' mail = MIMEText(body.encode(encoding),'plain',encoding) mail['Subject'] = Header(subject,encoding) mail['From'] = fromMail mail['To'] = toMail mail['Date'] = formatdate() try: #连接smtp服务器,明文/SSL/TLS三种方式,根据你使用的SMTP支持情况选择一种 #普通方式,通信过程不加密 smtp = smtplib.SMTP(smtpHost,smtpPort) smtp.ehlo() smtp.login(username,password) #tls加密方式,通信过程加密,邮件数据安全,使用正常的smtp端口 #smtp = smtplib.SMTP(smtpHost,smtpPort) #smtp.set_debuglevel(True) #smtp.ehlo() #smtp.starttls() #smtp.ehlo() #smtp.login(username,password) #纯粹的ssl加密方式,通信过程加密,邮件数据安全 #smtp = smtplib.SMTP_SSL(smtpHost,sslPort) #smtp.ehlo() #smtp.login(username,password) #发送邮件 smtp.sendmail(fromMail,toMail,mail.as_string()) smtp.close() print 'OK' except Exception as e: print e
各种元素都包含的邮件
#!/usr/bin/env python3 #coding: utf-8 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage sender = 'xxxx@163.com' receiver = 'xxxx@126.com' subject = '这是邮件主题' smtpserver = 'smtp.163.com' username = 'xxxx@163.com' password = '****' # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) #构造附件 att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="1.jpg"' msg.attach(att) if __name__=='__main__': smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
群发邮件技巧:
# 实践发现需要将msg['To'] = receiver修改为以下形式
msg["To"] = ",".join(receiver)
receiver是收件人列表。
用outlook邮箱发送(仅在windows下有效)
同事写的代码,
#coding=utf-8 import warnings import os import sys import lib.util as util import platform if not platform.system() == 'Linux': import win32com.client as win32 import pythoncom reload(sys) sys.setdefaultencoding('utf8') warnings.filterwarnings('ignore') DEFAULT_TEMPLATE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data","result","report.html") def sendmail(): print "mail_file = " + DEFAULT_TEMPLATE receiver = util.get_mail_conf("recevicer") htmlfile = open(DEFAULT_TEMPLATE) sub="Test Report" htmlbody = htmlfile.read() outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.BodyFormat = 2 mail.To = receiver mail.Subject = sub.decode('utf-8') mail.HTMLBody = htmlbody.decode("utf-8") mail.Attachments.Add(DEFAULT_TEMPLATE) mail.Send()
exchangelib应该是windows和Linux都能用的,但我发送失败了。尝试解决但失败了,原因不明。