利用本地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 = ''
sslPort = ''
fromMail = 'zhangsan@126.com'
toMail = 'funame@126.com'
username = 'zhangsan'
password = '' #邮件标题和内容
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都能用的,但我发送失败了。尝试解决但失败了,原因不明。

python发送邮件心得体会的更多相关文章

  1. Python学习心得体会总结,不要采坑

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:樱桃小丸子0093   大家要持续关注哦,不定时更新Python知识 ...

  2. 从实例学习 Go 语言、"基础与进阶" 学习笔记及心得体会、Go指南

    第一轮学习 golang "基础与进阶"学习笔记,Go指南练习题目解析.使用学习资料 <Go-zh/tour tour>.记录我认为会比较容易忘记的知识点,进行补充,整 ...

  3. python发送邮件

    python发送邮件(无附件) ======================================================= #!/usr/bin/env python#coding ...

  4. 关于Solr的使用总结的心得体会

    摘要:在项目中使用Solr作为搜索引擎对大数据量创建索引,提供服务,本文是作者对Solr的使用总结的一点心得体会, 具体包括使用DataImportHandler从数据库中近实时同步数据.测试Solr ...

  5. python发送邮件及附件

    今天给大伙说说python发送邮件,官方的多余的话自己去百度好了,还有一大堆文档说实话不到万不得已的时候一般人都不会去看,回归主题: 本人是mac如果没有按照依赖模块的请按照下面的截图安装 导入模块如 ...

  6. python学习心得第五章

    python学习心得第五章 1.冒泡排序: 冒泡是一种基础的算法,通过这算法可以将一堆值进行有效的排列,可以是从大到小,可以从小到大,条件是任意给出的. 冒泡的原理: 将需要比较的数(n个)有序的两个 ...

  7. python学习心得第四章

     python 学习心得第四章 1.lambda表达式 1:什么是lambda表达式 为了简化简单函数的代码,选择使用lambda表达式 上面两个函数的表达式虽然不一样,但是本质是一样的,并且lamb ...

  8. python学习心得第三章

    python学习心得第三章 1.三元运算 变量=值1 if 条件 else 值2 由图如果条件成立则赋值1给变量,如果条件不成立则赋值2给变量. 2.数据类型 集合:set() class set(o ...

  9. 加快FineReport报表设计的几个心得体会

    加快FineReport报表设计的几个心得体会 一.从远程服务器大批量取数进行表样设计时,最好按“列顺序”取一个“空的SQL语句”,这样可提高设计速度.否则每次设计时模板均要从远程读取数据,速度相当慢 ...

随机推荐

  1. Java Web环境搭建

    ——————————JavaWeb环境搭建 先下载JDK, Tomcat 7.0 安装JDK后,配置环境变量,此处可参考博客: https://www.cnblogs.com/smyhvae/p/37 ...

  2. js分析 有_道_翻_译 md5

    0.参考 1.分析 1.1 输入翻译内容,手动点击“翻译”按钮 1.2 查看提交数据,通过多次提交确认变化量 1.3 CTRL+SHIFT+f 全局搜索 salt 或 sign 定位到三处js代码块, ...

  3. 02.Control

    01.if ''' 제어문 = 조건문(if) + 반복문(while, for) 조건문 기본 형식1) python 블럭 if 조건식 : 실행문 실행문 cf) c언어 블럭 if 조건식 { ...

  4. SOUI taobao SVN目录结构说明

  5. Git基本操作指令

    Git是世界上目前最先进的分布式版本控制系统. 工作原理图: Workspace工作区,Index暂存区,Repository本地仓库区,Remote远程仓库. SVN与Git的最主要的区别? SVN ...

  6. PSO:利用PSO+ω参数实现对一元函数y = sin(10*pi*x) ./ x进行求解优化,找到最优个体适应度—Jason niu

    x = 1:0.01:2; y = sin(10*pi*x) ./ x; figure plot(x, y) title('绘制目标函数曲线图—Jason niu'); hold on c1 = 1. ...

  7. Urozero Autumn 2016. BAPC 2016

    A. Airport Logistics 根据光路最快原理以及斯涅尔定律,可以得到从定点$P$进入某条直线的最佳入射角. 求出每个端点到每条线段的最佳点,建图求最短路即可. 时间复杂度$O(n^2\l ...

  8. python进阶篇

    python进阶篇 import 导入模块 sys.path:获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到. ​ import sys ...

  9. MVC中EF代码优先问题

    在练习Mvc项目时,提示如下数据库错误: The model backing the 'EFDbContext' context has changed since the database was ...

  10. 重构file_get_contents实现一个带超时链接访问的函数

    function wp_file_get_contents($url, $timeout = 30) { $context = stream_context_create(array( 'http' ...