监控系统需要触发报警邮件, 简单笔记一下的用到的库.

smtplib

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

返回一个 smtp 实例, 如果指定了 host 和 port, 会调用 SMTP.connect() 进行连接, timout 指定超时时间

class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])

返回一个 ssl 模式的 smtp 实例, 仅在 SMTP.starttls() 无法或不推荐时使用

SMTP.set_debuglevel(level)

设置 debug 输出级别. 如果 level 设定为真值, 则会输出所有的调试信息和整个连接过程中收到和发送的信息.

SMTP.connect([host[, port]])

连接到指定 host 的端口. 默认 host 为 localhost, 默认端口为25

SMTP.helo([hostname])

跟 SMTP 邮件服务器介绍下自己, 一般情况下不需要直接执行此命令, 直接调用 SMTP.sendmail()

SMTP.ehlo([hostname])

跟 ESMTP 邮件服务器 say hello

SMTP.verify(address)

确认邮件地址的有效性, 如果有效会返回 code 250 和完成的有点地址, 大部分邮件服务器会屏蔽此命令以防垃圾邮件

SMTP.login(userpassword)

登录到邮件服务器

SMTP.starttls([keyfile[, certfile]])

将 smtp 连接切换到 tls 模式

SMTP.sendmail(from_addrto_addrsmsg[, mail_optionsrcpt_options])

发邮件

from_addr    string    发件人

to_addrs       list        收件人

msg             string     信息

SMTP.quit()

终止 smtp 会话, 关闭链接.

SMTP Example

import smtplib

def prompt(prompt):
return raw_input(prompt).strip() fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):" # Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

注意到 msg 需要添加一个邮件头, 格式是

"""

From: test@gmail.com

To: test@gmail.com, test1@gmail.com, test2@gmail.com

邮件正文

"""

显然这样攒 msg 不是一个好办法, 所以 python 提供了 email

邮件发送 html

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText # me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you # Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="https://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) # Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

1. 注意到 MIMEMultipart 和 MIMEText, 从返回对象的关系看, MIMEText 的对象可以被 attach 到 MIMEMultipart 返回的对象上

2. 如果实际测试这段代码, 会发现虽然 attach 两次, 但是收到的只有一个 html 的内容, 这跟 MIMEMultipart("alternative") 有关

3. 如果初始化时选择 MIMEMultipart("mixed"), 会发现邮件内容是 text 文本, 同时携带一个 .html 的附件

4. 如果只选择 attach(part2), 发现邮件内容是 html

5. MIMEMultipart 的实例, 包含邮件标题 Subject, 发件人 From, 收件人 To, 最后 attach MIMEText 的实例

6. 这里注意, 如果有多个收件人, To 应该是以 ; 间隔的字符串,  虽然使用 , 间隔也可以成功, 但是 ; 是标准的写法

7. 这跟 sendmail 中的收件人是不同的, sendmail 中的收件人是 list 列表, 如果把 To 作为参数传给 sendmail, 那么只会有第一个人收到邮件

class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])

_subtype

multipart/mixed

A number of different resources are combined in a single message.

multipart/alternative

The section 5.1.4 of RFC 2046 defines multipart/alternative MIME type to allow the sender to provide different, interchangeable representations of the same message and to leave it up to the receiver to chose the form of presentation most suitable for its capabilities

class email.mime.text.MIMEText(_text[, _subtype[, _charset]])

如果发送中文, 需要指定 _charset="utf8"

python smtplib email的更多相关文章

  1. python操作email

    python操作email 参考链接: python官网imaplib: https://docs.python.org/2/library/imaplib.html Python 用IMAP接收邮件 ...

  2. python email ==> send 发送邮件 :) [smtplib, email 模块]

    关于Email的预备知识: 原贴地址:http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343480.html ############ ...

  3. 【Python】 发邮件用 smtplib & email

    smtplib & email ■ 概述 发邮件主要用到smtplib以及email模块.stmplib用于邮箱和服务器间的连接,发送的步骤.email模块主要用于处理编码,邮件内容等等.主要 ...

  4. 使用python的email、smtplib、poplib模块收发邮件

    使用python的email.smtplib.poplib模块收发邮件 一封电子邮件的旅程是: MUA:Mail User Agent——邮件用户代理.(即类似Outlook的电子邮件软件) MTA: ...

  5. [Python] 发送email的几种方式

    python发送email还是比較简单的,能够通过登录邮件服务来发送,linux下也能够使用调用sendmail命令来发送,还能够使用本地或者是远程的smtp服务来发送邮件,无论是单个,群发,还是抄送 ...

  6. 使用python调用email模块发送邮件附件

    使用python调用email模块实现附件发送 需要模块: import datetime import time import sys import mimetypes import smtplib ...

  7. python smtplib 发送邮件简单介绍

    SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式python的smtplib提供了一种很 ...

  8. Python 发送 email 的两种方式

    Python发送email的两种方式,分别为使用登录邮件服务器.调用sendmail命令来发送三种方法 Python发送email比较简单,可以通过登录邮件服务来发送,linux下也可以使用调用sen ...

  9. Python_使用smtplib+email完成邮件发送

    本文以第三方QQ邮箱服务器演示如何使用python的smtplib+email完成邮箱发送功能 一.设置开启SMTP服务并获取授权码 开启QQ邮箱SMTP服务 开启的最后一步是发送短信验证,获取 au ...

随机推荐

  1. 通过实战理解C语言精要——函数篇

      前言 本篇博客是对C语言函数部分的重点内容和细枝末节通过实战得到的经验的总结精炼,不涵盖C语言函数的全部内容,所有提炼内容均来自提炼与实战,阅读需要对函数部分有一定基础,可用于对C语言函数的理解提 ...

  2. Android6.0动态申请权限

    先直接看代码: public void onClick(View v){ onCallPermission(); } public void onCallPermission(){ if (Build ...

  3. C 语言学习 第三次作业总结

    本次作业内容: For循环的使用 If判断语句的使用 常用数学运算表达式的使用 数学函数库中几个常见函数的使用及自我实现 将操作代码提交到coding 作业总结: For循环是C语言中一种基本的循环语 ...

  4. hibernate在使用getCurrentSession时提示no session found for current thread

    大致错误片段 org.hibernate.HibernateException: No Session found for current thread at org.springframework. ...

  5. C#-WebForm-ASP开发练习:从数据库中动态添加信息

    传统的ASP开发方式,是C#代码和HTML代码混合在一起,ASP与ASP.NET不是一个东西. <%  %>  -  可以扩起来一段范围,这一段范围之内只能允许编写C#代码 <%= ...

  6. Ubuntu使用MyEclipse闪退的解决办法

    修改myeclipse.ini文件, -Xmx512m-XX:MaxPermSize=512m-XX:ReservedCodeCacheSize=256m-Dosgi.nls.warnings=ign ...

  7. 【Codeforces720D】Slalom 线段树 + 扫描线 (优化DP)

    D. Slalom time limit per test:2 seconds memory limit per test:256 megabytes input:standard input out ...

  8. XSS攻击测试代码

    '><script>alert(document.cookie)</script>='><script>alert(document.cookie)&l ...

  9. JSVirtualMachine与JSContext

    JSVirtualMachine相当于进程: JSContext相当于线程:

  10. fscanf()函数基本用法

    FILE *fp; while(!feof(fp)) { fscanf(fp,"%s%d%lf",a,&b,&c);//这里%s对应的a不需要加上取地址符号& ...