python中怎么实现一次性发多个邮件

男朋友 0 110

python中怎么实现一次性发多个邮件,第1张

python中怎么实现一次性发多个邮件
导读:首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件,而大多数的邮件发送服务器都是使用SMTP协议。SMTP协议的默认TCP端口号是25。

首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件,而大多数的邮件发送服务器都是使用SMTP协议。SMTP协议的默认TCP端口号是25。

本文主要介绍利用'smtplib','email'两个模块来实现邮件的发送,可以如下查看两个模块的函数和方法:

smtplib模块简介:

smtplibSMTP([host[, port[, local_hostname[, timeout]]]])

  此为SMTP类构造函数,表示与SMTP服务器之间的连接,并根据这个连接向smtp服务器发送指令,执行相关操作(如:登陆、发送邮件),且每个参数都是可选的。

其中最重要的参数:

host:smtp服务器主机名

port:smtp服务的端口,默认是25;

如果在创建SMTP对象的时候提供了这两个参数,在初始化的时候会自动调用connect方法去连接服务器。

smtplibSMTP还提供了如下方法:

SMTPset_debuglevel(level):设置是否为调试模式

SMTPconnect([host[, port]]):连接到指定的smtp服务器。参数分别表示 smpt主机和端口。

SMTPdocmd(cmd[, argstring]):向smtp服务器发送指令。

SMTPhelo([hostname]) :使用"helo"指令向服务器确认身份。

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

SMTPsendmail(from_addr,to_addrs,msg[,mail_options,rcpt_options]):发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。SMTPquit() :断开与smtp服务器的连接,相当于发送"quit"指令。(重要!)

常用的函数方法:

email模块

1class emailmessageMessage

__getitem__,__setitem__实现obj[key]形式的访问。

Msgattach(playload): 向当前Msg添加playload。

Msgset_playload(playload):

Msgadd_header(_name, _value, _params): 添加邮件头字段。

2class emailmimebaseMIMEBase(_maintype, _subtype, _params)

所有MIME类的基类,是emailmessageMessage类的子类。

3class emailmimemultipartMIMEMultipart()

在30版本的email模块 (Python 23-Python 25) 中,这个类位于emailMIMEMultipartMIMEMult ipart。这个类是MIMEBase的直接子类,用来生成包含多个部分的邮件体的MIME对象。

4class emailmimetextMIMEText(_text)

使用字符串_text来生成MIME对象的主体文本。

获得所需要使用的邮箱的host地址和port端口号,(本文使用的是163邮箱,对应的smtp服务器地址:mail163com,端口号25)

常用邮箱的smtp服务器地址和端口号如图:

编写程序如下:

#! /usr/bin/env python

import smtpli

from emailmimetext import MIMEText

mailto_list=['xxxx@xxxcom'] #收件人(列表)

mail_host="smtp163com" #使用的邮箱的smtp服务器地址

mail_user="name" #用户名

mail_pass="pwd" #密码

mail_postfix="postfix" #邮箱的后缀

def send_mail(to_list,sub,content):

me="hello"+"<"+mail_user+"@"+mail_postfix+">"

msg = MIMEText(content,_subtype='plain')

msg['Subject'] = sub

msg['From'] = me

msg['To'] = ";"join(to_list) #将收件人列表以‘;’分隔

try:

server = smtplibSMTP()

serverconnect(mail_host) #连接服务器

serverlogin(mail_user,mail_pass) #登录操作

serversendmail(me, to_list, msgas_string())

serverclose()

return True

except Exception, e:

print str(e)

return False

for i in range(5): #发送五封,不过会被拦截的。。。

if send_mail(mailto_list,"hello","haha!"): #邮件主题和邮件内容

print "done!"

else:

print "failed!"

最后,可以运行编写的py文件,可以得到如图所是的结果,代表邮件发送成功。

这样,就能成功实现用Python发送邮件啦!

1、发送邮件:

import zmail

server = zmailserver(' yourmail@examplecom ’, 'yourpassword')

serversend_mail(' yourfriend@examplecom ',{'subject':'Hello!','content_text':'By zmail'})

serversend_mail([' friend1@examplecom ',' friend2@examplecom '],{'subject':'Hello!','content_text':'By zmail'})

2、接收最后一封邮件:

import zmail

server = zmailserver(' yourmail@examplecom ’, 'yourpassword')

latest_mail = serverget_latest()

zmailshow(latest_mail)

3、发送带附件的邮件:

import zmail

mail = {

'subject': 'Success!', # Anything you want

'content_text': 'This message from zmail!', # Anything you want

'attachments': ['/Users/zyh/Documents/examplezip','/root/1jpg'], # Absolute path will be better

}

server = zmailserver(' yourmail@examplecom ’, 'yourpassword')

serversend_mail(' yourfriend@examplecom ', mail)

serversend_mail([' yourfriend@examplecom ',' 12345@examplecom '], mail)

4、发送html格式邮件:

with open('/Users/examplehtml','r') as f:

content_html = fread()

mail = {

'subject': 'Success!', # Anything you want

'content_html': content_html,

'attachments': '/Users/zyh/Documents/examplezip', # Absolute path will be better

}

serversend_mail(' yourfriend@examplecom ',mail)

5、使用抄送:

serversend_mail([' foo@163com ',' foo@126com '],mail,cc=[' bar@163com '])

6、自定义server

server = zmailserver('username','password',smtp_host='smtp163com',smtp_port=994,smtp_ssl=True,pop_host='pop163com',pop_port=995,pop_tls=True)

7、根据ID取回邮件:mail = serverget_mail(2)

根据日期、主题、发送人取回邮件:

mail = serverget_mails(subject='GitHub',after='2018-1-1',sender='github')

mail = serverget_mails(subject='GitHub',start_time='2018-1-1',sender='github',start_index=1,end_index=10)

8、查看邮箱统计

mailbox_info = serverstat() #结果为包含两个整型的元组: (邮件的数量, 邮箱的大小)

9、删除邮件:MailServerdelete(which)

10、保存附件:zmailsave_attachment(mail,target_path=None,overwrite=False)

11、保存邮件:zmailsave(mail,name=None,target_path=None,overwrite=False)

12、读取邮件:zmailread(file_path,SEP=b'\r\n')

支持的列表:

msg['To'] = "a@mailcom;b@mailcom" # 多个邮件接收者,中间用;隔开

msg['Cc'] = "c@mailcom;d@mailcom" # 多个邮件抄送者,中间用;隔开