Python SMTP服务发送邮件
程序员文章站
2022-03-18 09:35:01
...
- 首选需要拥有自己的SMTP服务器,为了方便我选择使用QQ的SMTP服务。所有首先启动QQ邮箱的SMTP服务,具体启用方式:登录QQ邮箱=》设置=》账户:
此时会生成授权码,授权码为QQSMTP服务器的密码,账户为当前邮箱账户。
2.简单的发送邮件SMTP(不含附件)
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#设置发送者
sender='aaa@qq.com'
#设置接受者
receivers= ['aaa@qq.com']
#主题名称
subject = 'hellow word'
#设置邮件内容
message = MIMEText('this is a example send by python smtp','plain','utf-8')
#发送者名称
message['From'] = Header('jecat','utf-8')
#接收者名称
message['To'] = Header('example','utf-8')
#邮件主题或者标题
message['Subject'] = Header(subject,'utf-8');
try:
#设置SMTP服务器地址
smtpobj = smtplib.SMTP_SSL('smtp.qq.com',465)
#登录SMTP服务器
smtpobj.login('aaa@qq.com','服务器授权码');
#发送邮件
smtpobj.sendmail(sender,receivers,message.as_string());
print('邮件发送成功')
except BaseException as msg:
print('邮件发送失败'),
print(msg);
测试结果:
3.发送邮件带附件SMTP
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
#设置发送者
sender='aaa@qq.com'
#设置接受者
receivers= ['aaa@qq.com']
#主题名称
subject = 'hellow word'
#设置邮件内容
message = MIMEMultipart()
#发送者名称
message['From'] = Header('jecat','utf-8')
#接收者名称
message['To'] = Header('example','utf-8')
#邮件主题或者标题
message['Subject'] = Header(subject,'utf-8');
#设置邮件正文
text = MIMEText('email conetnet example','plain','utf-8')
message.attach(text);
#构造附件,上传e:\python\client.py e:\python\server.py
#上传文件位置
upfiles = ['e:\python\client.py','e:\python\server.py']
#上传文件服务器保存的名称
filenams = ['client.py','server.py']
for index in range(len(upfiles)):
try:
attr = MIMEText(open(upfiles[index],'r+b').read(),'base64','utf-8')
attr['Content-Type']='application/octet-stream'
filename = '{0}{1}'.format('attachment; filename=',filenams[index])
attr["Content-Disposition"] = filename
message.attach(attr)
except BaseException as msg:
print("read filed failed %s"%msg)
pass
try:
#设置SMTP服务器地址
smtpobj = smtplib.SMTP_SSL('smtp.qq.com',465)
#登录SMTP服务器
smtpobj.login('aaa@qq.com','服务器授权码');
#发送邮件
smtpobj.sendmail(sender,receivers,message.as_string());
print('邮件发送成功')
smtpobj.close();
except BaseException as msg:
print('邮件发送失败'),
print(msg);
smtpobj.close();
4.读取邮件并且下载附件POP3
发现使用pop.qq.com取到的文件数量比实际少??
import poplib
import email
from email.mime.text import MIMEText
from email.header import decode_header
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr
from email.parser import Parser
#对邮件内容的文字进行解码
def decode_str(s):
val,charset = decode_header(s)[0]
if charset:
val = val.decode(charset)
return val
#猜测内容编码方式
def guess_chart(msg):
#获取msg的编码
chartset = msg.get_charset()
if chartset is None:
#如果获取不到则从content-type里面获取
content_type = msg.get('Content-Type','').lower()
pos = content_type.find('charset=')
if pos >= 0:
chartset = content_type[pos+8:].strip()
return chartset
#获取emial的文件头里面的内容
def get_email_object(email_msg,itemname):
item_val = email_msg.get(itemname,'')
if item_val:
if itemname == 'Subject':
#解码subject
return decode_str(item_val)
if itemname == 'From' or itemname == 'To':
#解析发送者的名称和地址
hdr,addr = parseaddr(item_val)
name = decode_str(hdr)
return '%s <%s>' % (name,addr)
else:
return item_val
try:
#设置SMTP服务器地址
popobj = poplib.POP3_SSL('pop.qq.com')
print(popobj.getwelcome());
#登录SMTP服务器
popobj.user('aaa@qq.com')
popobj.pass_("服务器授权码")
#获取邮箱信息
messagecount,messagesize = popobj.stat();
print('邮件个数:%d' % messagecount)
print('邮件大小:%d' % messagesize)
#获取邮件
resp,mails,octets = popobj.list();
#邮件响应结果bok
print(resp);
#邮件列表(下标,大小 ....)
print(mails);
print(octets);
print('****************************************************************************************')
for index in range(1,len(mails)):
# lines 存储原始邮件的每行数据
resp, lines, octets = popobj.retr(index)
#将每一行的内容合并成一个字符串,注意这里需要是bytes
msg_content = b'\r\n'.join(lines)
#开始解析邮件内容,这里需要是text
msg = Parser().parsestr(msg_content.decode())
#解析Emai的基本信息 From To Date Subject
print(msg.get_content_type())
EmailHeader = {}
EmailHeader['From'] = get_email_object(msg, 'From')
EmailHeader['To'] = get_email_object(msg, 'To')
EmailHeader['Date'] = get_email_object(msg, 'Date')
EmailHeader['Subject'] = get_email_object(msg, 'Subject')
print(EmailHeader)
print('****************************************************************************************')
#这里下载邮件附件,保存在当前路径下面
for part in msg.walk():
filename = part.get_filename()
content_type = part.get_content_type()
#保存附件,filename 为附件名称
if filename:
#解码文件名称
h = decode_str(filename)
#获取文件内容
data = part.get_payload(decode=True)
att_file = open('./download/'+h,'w+b');
att_file.write(data)
att_file.close()
print('download file=%s' % h)
#保存邮件正文,并不写文件,可以根据文件类型写文件
elif content_type == 'text/plain' or content_type == 'text/html':
data = part.get_payload(decode=True)
charset = guess_chart(part)
if charset:
charset = charset.strip().split(';')[0]
data = data.decode(charset)
print(data)
except BaseException as msg:
print('邮件发送失败'),
print(msg);
上一篇: phpmyadmin怎样修改主键
下一篇: 数据类型转换
推荐阅读