Python 学习-发送 email 的两种方式代码!

  • A+
所属分类:Python学习

Python 学习-发送 email 的两种方式代码!

 

Python发送email的两种方式,分别为使用登录邮件服务器、调用sendmail命令来发送两种方法。

 

Python发送email比较简单,可以通过登录邮件服务来发送,linux下也可以使用调用sendmail命令来发送,还可以使用本地或者是远程的smtp服务来发送邮件,不管是单个,群发,还是抄送都比较容易实现。先介绍几个最简单的发送邮件方式记录下,像html邮件,附件等也是支持的,需要时查文档即可。

一、登录邮件服务器

通过smtp登录第三方smtp邮箱发送邮件,支持 25 和 465端口

vim python_email_1.py

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #
  4. # author: mimvp.com
  5. # 2015.10.05
  6. import smtplib
  7. from email.mime.text import MIMEText
  8. smtpHost = 'smtp.exmail.qq.com'
  9. sender = 'robot@mimvp.com'
  10. password = "mimvp-password"
  11. receiver = 'yanggang@mimvp.com'
  12. content = 'hello mimvp.com'
  13. msg = MIMEText(content)
  14. msg['Subject'] = 'email-subject'
  15. msg['From'] = sender
  16. msg['To'] = receiver
  17. ## smtp port 25
  18. smtpServer = smtplib.SMTP(smtpHost, 25) # SMTP
  19. smtpServer.login(sender, password)
  20. smtpServer.sendmail(sender, receiver, msg.as_string())
  21. smtpServer.quit()
  22. print 'send success by port 25'
  23. ## smtp ssl port 465
  24. smtpServer = smtplib.SMTP_SSL(smtpHost, 465) # SMTP_SSL
  25. smtpServer.login(sender, password)
  26. smtpServer.sendmail(sender, receiver, msg.as_string())
  27. smtpServer.quit()
  28. print 'send success by port 465'

执行命令:

$ python python_email_1.py
send success by port 25
send success by port 465

二、调用sendmail命令

调用本机linux自身sendmail服务发送邮件,不需要启动sendmail后台进程,不需要发送者登录,邮件发送者可以是任意名字,没有限制。

特别注意:sendmail 命令发送邮件,默认用25端口号,由于阿里云、腾讯云等封禁了25端口号,因此本示例需在开通25端口机器上测试

vim python_email_3.py

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #
  4. # author: mimvp.com
  5. # 2015.10.05
  6. from email.mime.text import MIMEText
  7. from subprocess import Popen, PIPE
  8. import commands
  9. import sys
  10. reload(sys)
  11. sys.setdefaultencoding('utf-8')
  12. def send_mail(sender, recevier, subject, html_content):
  13. msg = MIMEText(html_content, 'html', 'utf-8')
  14. msg["From"] = sender
  15. msg["To"] = recevier
  16. msg["Subject"] = subject
  17. p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
  18. p.communicate(msg.as_string())
  19. sender = 'robot@mimvp.com'
  20. recevier = 'yanggang@mimvp.com'
  21. subject = 'sendmail-subject'
  22. html_content = 'hello mimvp.com'
  23. send_mail(sender, recevier, subject, html_content)

执行命令:

python python_email_3.py

 

学习资料见知识星球。

以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。

快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利​​​​!

更多技巧, www.excelbook.cn

欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;

Python 学习-发送 email 的两种方式代码!

你将获得:

1、价值上万元的专业的PPT报告模板。

2、专业案例分析和解读笔记。

3、实用的Excel、Word、PPT技巧。

4、VIP讨论群,共享资源。

5、优惠的会员商品。

6、一次付费只需99元,即可下载本站文章涉及的文件和软件。

  • 我的微信
  • weinxin
  • 我的知识星球
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: