python发送邮件之SMTP

编程入门 行业动态 更新时间:2024-10-09 00:48:24

python<a href=https://www.elefans.com/category/jswz/34/1770428.html style=发送邮件之SMTP"/>

python发送邮件之SMTP

简述:
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
常用邮箱的smtp服务器地址:
新浪邮箱:smtp.sina,搜狐邮箱:smtp.sohu,qq邮箱:smtp.qq

1、SMTP

创建SMTP语法:

import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )参数说明:host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:runoob,这个是可选参数。
port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下SMTP端口号为25。
local_hostname: 如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。

SMTP对象使用sendmail方法发送邮件语法

smtplib.SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]参数说明:from_addr: 邮件发送者地址。
to_addrs: 字符串列表,邮件发送地址。
msg: 发送消息
这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。

2、email模块的详细理解和使用

A、from email.mime.text import MIMEText 构造文本邮件

MIMEText对象中有三个参数依次为:正文内容、正文内容的类型、编码

message = MIMEText(‘邮件正文’, ‘plain’, ‘utf-8’) 例如:”text/plain”和”text/html”

简单的文本

简单的文本
text_info = 'hello world '
text_sub = MIMEText(text_info,'plain', 'utf-8')#实例1
import smtplib
from email.mime.text import MIMEText
user='512044050@qq'#发件箱
pwd='xofoxzeqmyjzcagc'#发件箱服务器授权码
you='1049252083@qq'#收件箱
smtp_add='smtp.qq'#邮箱服务器text='我是邮件内容'#邮件内容
msg=MIMEText(text,'plain','utf-8')
msg['From']=user#发件人,会在邮箱中展示
msg['To']=you#收件人,会在邮箱中展示
msg['Cc']=you#抄送
msg['Subject']='测试发送纯文本'#邮件主题
smtp=smtplib.SMTP_SSL(smtp_add,465)#实例化服务器对象
smtp.login(user,pwd)#登录服务器
smtp.sendmail(user,you,msg.as_string())#发送邮件
smtp.quit()#实例2
#在文件读取内容作为邮件正文以及把邮件正文写入文件当作附件发送
from email.mime.text import MIMEText
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'# ---------------------读取txt文件内容作为邮件正文,同时作为附件上传---------------------
with open('D:\PROJECT\lunwen\AL电厂经营战略分析.txt',encoding='utf-8') as f:result=f.read()
msg=MIMEText(result,'plain','utf-8')
#把文件内容写入csdn.txt中同时当作附件上传
msg["Content-Disposition"] = 'attachment; filename="csdn.txt"'
msg['From']=user
msg['To']=you
msg['Cc']=you#抄送
msg['Subject']='测试2号'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,msg.as_string())#发送邮件
smtp.quit()

构造超文本

html_info = """<p>点击以下链接,你会去向一个更大的世界</p><p><a href="%s">click me</a></p><p>i am very glasses for you</p>""" % url
html_sub = MIMEText(html_info, 'html', 'utf-8')  
# 这行代码会把上面的内容同时放入html文件里面作为附件发送
html_sub["Content-Disposition"] = 'attachment; filename="csdn.html"'实例:
#同时发送超文本内容并把内容作为附件发送
from email.mime.text import MIMEText
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'
url=''
html_info = """<p>点击以下链接,你会去向一个更大的世界</p><p><a href="%s">click me</a></p><p>i am very glasses for you</p>""" % url
msg = MIMEText(html_info, 'html', 'utf-8')
# 这行代码会把上面的内容放入html文件里面作为附件上传
msg["Content-Disposition"] = 'attachment; filename="csdn.html"'
msg['From']=user
msg['To']=you
msg['Cc']=you#抄送msg['Subject']='测试2号'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,msg.as_string())#发送邮件
smtp.quit()#超文本嵌套图片显示在正文
h='<html><body><img src=".jpeg" alt="imageid"></body></html>'
msg=MIMEText(h,'html','utf-8')

构造base64数据流,用于发送文件的时候使用,构造附件代码: ~~

txt_file = open(r'D:\python_files\files\hello_world.txt', 'rb').read()
txt = MIMEText(txt_file, 'base64', 'utf-8')
txt["Content-Type"] = 'application/octet-stream'命名发送的附件
txt.add_header('Content-Disposition', 'attachment', filename='hello_world.txt')#实例:
#构造附件from email.mime.text import MIMEText
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'f=open('D:\PROJECT\lunwen\AL电厂经营战略分析.txt','rb').read()
msg=MIMEText(f,'base64','utf-8')
msg["Content-Type"] = 'application/octet-stream'#把文件内容写入csdn.txt中当作附件上传
msg.add_header('Content-Disposition', 'attachment', filename='hello_world.txt')
# msg["Content-Disposition"] = 'attachment; filename="csdn.txt"'#上面的效果一下msg['From']=user
msg['To']=you
msg['Cc']=you#抄送msg['Subject']='测试2号'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,msg.as_string())#发送邮件
smtp.quit()

B、from email.mime.image import MIMEImage 构造图片邮件

构造图片

mage_file = open(r'D:\python_files\images\test.png', 'rb').read()
image = MIMEImage(image_file)
image.add_header('Content-ID', '<image1>')
# 命名发送的图片
image["Content-Disposition"] = 'attachment; filename="red_people.png"'实例:
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'
#打开图片
with open('D:\PROJECT\picture\AL电厂经营战略分析.png','rb') as f:pg=f.read()
msg=MIMEImage(pg)
# msg.add_header('Content-ID', '<image1>')
# 作为附件上传
msg["Content-Disposition"] = 'attachment; filename="red_people.png"'msg['From']=user
msg['To']=you
msg['Cc']=you#抄送
msg['Subject']='测试2号'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,msg.as_string())#发送邮件
smtp.quit()

C、from email.mime.multipart import MIMEMultipart 要把多个对象组合起来*

IMEMultipart对象创建的三种类型,此模块主要是通过attach方法把上边构造的内容传入到邮件的整体内容中:
1、邮件类型为”multipart/alternative”的邮件正文中包括纯文本正文(text/plain)和超文本正文(text/html)。
2、邮件类型为”multipart/related”的邮件正文中包括图片,声音等内嵌资源。
3、邮件类型为”multipart/mixed”的邮件包含附件,图片,文本等都可以添加,所以发的内容多的话一般是用这个的,选择mixed类型,什么内容都可以发。

3、邮件头添加内容

from email.header import Header
"""省略一万字"""
# 邮件主题
subject = 'python sendemail test successful'
msg_root['subject'] = Header(subject, 'utf-8')

综合练习:


----------------------------练习1------------------------
from email.mime.multipart import MIMEMultipart#组合多个邮件对象
from email.mime.image import MIMEImage  #构造图片
from email.mime.text import MIMEText    #构造文本
from email.header import Header
import smtplib
def sendMail(you):user='512044050@qq'pwd='xofoxzeqmyjzcagc'#设置总的邮件对象ME=MIMEMultipart('mixed')#邮件头尾信息ME['From']=user#发件人ME['To']=you#收件人ME['Cc']=you#抄送m='你好  杨小姐'#邮件主题ME['Subject']=Header(m,'utf-8')# 构造文本内容with open('D:\PROJECT\lunwen\Z公司绩效管理有效性研究.txt',encoding='utf-8') as f:res=f.read()msg=MIMEText(res,'plain','utf-8')#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容msg["Content-Disposition"] = 'attachment; filename="csdn.txt"'ME.attach(msg)#添加到邮件整体内容中#构造图片image_file = open('D:\PROJECT\picture\AL电厂经营战略分析.png', 'rb').read()msg = MIMEImage(image_file)msg.add_header('Content-ID', '<image1>')# 如果不加下边这行代码的话,会在收件方方面显示bin文件,下载之后也不能正常打开msg["Content-Disposition"] = 'attachment; filename="red_people.png"'ME.attach(msg)#添加到邮件整体内容中# 构造附件txt_file = open(r'D:\PROJECT\lunwen\“人性化”管理是企业管理的必然趋势.txt', 'rb').read()txt = MIMEText(txt_file, 'base64', 'utf-8')txt["Content-Type"] = 'application/octet-stream'#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容txt["Content-Disposition"] = 'attachment; filename="red_people.txt"'ME.attach(txt)#添加到邮件整体内容中#构造超文本url=''html_info = """<p>点击以下链接,你会去向一个更大的世界</p><p><a href="%s">click me</a></p><p>i am very galsses for you</p>"""% urlfg=MIMEText(html_info,'html','utf-8')#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容fg["Content-Disposition"] = 'attachment; filename="csdn.html"'ME.attach(fg)#添加到邮件整体内容中flage=Truewhile flage:try:smp=smtplib.SMTP('smtp.qq',25)smp.login(user,pwd)smp.sendmail(user,you,ME.as_string())print('邮件发送成功')breakexcept:print('邮件发送失败,尝试重新发送')break
if __name__=='__main__':sendMail('1049252083@qq')--------------------------------------------练习2------------------from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header
from bs4 import BeautifulSoup
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'
M=MIMEMultipart('mixed')
M['From']=user
M['To']=you
M['Cc']=you
d='测试发送HTML邮件'
M['Subject']=Header(d,'utf-8')#读取HTML文件并解析发送邮件
# with open('D:\PROJECT\\test_pytest\\report\html\\123.html','r',encoding='utf-8') as f:
#     res=f.read().title()
# soup=BeautifulSoup(res,'lxml')
# h=soup.find('h').text
# # print(h)
# msg=MIMEText(h,'plain','utf-8')
# msg["Content-Disposition"] = 'attachment; filename="red_people.html"'
# M.attach(msg)#读取HTML文件当作文件内容发送邮件
with open('D:\PROJECT\\test_pytest\\report\html\Selenium2Library.html') as f:res=f.read()
# print(res)
soup=BeautifulSoup(res,'lxml')
b=soup.find('body')
div=b.find('div')
result=[]
h=div.find('h1').text
result.append(h+'\n')
li_list=div.find_all('li')
for  li in li_list:result.append(li.text+'\n')
ret=''.join(result)
msg=MIMEText(ret,'plain','utf-8')
#加上下面这行代码正文将没有内容,当作附件上传
msg["Content-Disposition"] = 'attachment; filename="red_people.html"'
M.attach(msg)# 发送带图片的链接
# h='<html><body><img src=".jpeg" alt="imageid"></body></html>'
# msg=MIMEText(h,'html','utf-8')
# M.attach(msg)#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容
# msg["Content-Disposition"] = 'attachment; filename="csdn.png"'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,M.as_string())#发送邮件
smtp.quit()

读取HTMl文件发送其内容并且作为附件发送

import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoupsmtp_addr='smtp.qq'
me='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'#读取HTML文件当作文件内容发送邮件
with open('D:\PROJECT\\test_pytest\\report\html\Selenium2Library.html') as f:res=f.read()
#print(res)
soup=BeautifulSoup(res,'lxml')
b=soup.find('body')
div=b.find('div')
result=[]
h=div.find('h1').text
result.append(h+'\n')
li_list=div.find_all('li')
for  li in li_list:result.append(li.text+'\n')
ret=''.join(result)
msg=MIMEText(ret,'plain','utf-8')
#同时当作附件上传
msg["Content-Disposition"] = 'attachment; filename="red_people.html"'msg['From']=me
msg['To']=you
msg['Cc']=you
msg['Subject']='测试同时发送HTML邮件正文和附件'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(me,pwd)
smtp.sendmail(me,you,msg.as_string())
smtp.quit()

多个收件人和抄送人

import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
def send_mail(you):smtp_addr='smtp.qq'me='512044050@qq'pwd='xofoxzeqmyjzcagc'# #读取HTML文件当作文件内容发送邮件with open('D:\PROJECT\\test_pytest\\report\html\Selenium2Library.html') as f:res=f.read()# print(res)soup=BeautifulSoup(res,'lxml')b=soup.find('body')div=b.find('div')result=[]h=div.find('h1').textresult.append(h+'\n')li_list=div.find_all('li')for  li in li_list:result.append(li.text+'\n')ret=''.join(result)msg=MIMEText(ret,'plain','utf-8')#同时当作附件上传msg["Content-Disposition"] = 'attachment; filename="red_people.html"'msg['Subject']='测试同时发送HTML邮件正文和附件'msg['From'] = me  # 发件人list = [you, '1205129045@qq', '647712685@qq']msg['To'] = ','.join(list)  # 合并多个收件人l = ['1205129045@qq', '647712685@qq']msg['Cc'] = ','.join(l)  # 合并多个抄送人try:smtp=smtplib.SMTP(smtp_addr,25)smtp.login(me,pwd)smtp.sendmail(me,you,msg.as_string())smtp.quit()print('发送邮件成功')except:print('发送邮件失败')if __name__=="__main__":you='1049252083@qq'send_mail(you)

4、总结:

如果单独使用 MIMEText或者 MIMEImage,下面这个代码实现的功能不仅是发送文件正文而且会把正文当作附件发送

import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoupsmtp_addr='smtp.qq'
me='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'#读取HTML文件当作文件内容发送邮件
with open('D:\PROJECT\\test_pytest\\report\html\Selenium2Library.html') as f:res=f.read()
# print(res)
soup=BeautifulSoup(res,'lxml')
b=soup.find('body')
div=b.find('div')
result=[]
h=div.find('h1').text
result.append(h+'\n')
li_list=div.find_all('li')
for  li in li_list:result.append(li.text+'\n')
ret=''.join(result)
msg=MIMEText(ret,'plain','utf-8')
#同时当作附件上传
msg["Content-Disposition"] = 'attachment; filename="red_people.html"'msg['From']=me
msg['To']=you
msg['Cc']=you
msg['Subject']='测试同时发送HTML邮件正文和附件'smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(me,pwd)
smtp.sendmail(me,you,msg.as_string())
smtp.quit()

如果使用组合模块MIMEMultipart,实现的是要么发送为正文内容,要么是附件,只能选择其一,代码如下

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header
from bs4 import BeautifulSoup
import smtplib
smtp_addr='smtp.qq'
user='512044050@qq'
pwd='xofoxzeqmyjzcagc'
you='1049252083@qq'
M=MIMEMultipart('mixed')
M['From']=user
M['To']=you
M['Cc']=you
d='测试发送HTML邮件'
M['Subject']=Header(d,'utf-8')#读取HTML文件并解析发送邮件
#with open('D:\PROJECT\\test_pytest\\report\html\\123.html','r',encoding='utf-8') as f:#     	res=f.read().title()
#soup=BeautifulSoup(res,'lxml')
#h=soup.find('h').text
#print(h)
#msg=MIMEText(h,'plain','utf-8')
#msg["Content-Disposition"] = 'attachment; filename="red_people.html"'
#M.attach(msg)#发送带图片的链接
#h='<html><body><img src=".jpeg" alt="imageid"></body></html>'
#msg=MIMEText(h,'html','utf-8')#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容
#msg["Content-Disposition"] = 'attachment; filename="csdn.png"'#M.attach(msg)smtp=smtplib.SMTP(smtp_addr,25)
smtp.login(user,pwd)
smtp.sendmail(user,you,M.as_string())#发送邮件
smtp.quit()

实现发送正文和附件

from email.mime.multipart import MIMEMultipart#组合多个邮件对象
from email.mime.image import MIMEImage  #构造图片
from email.mime.text import MIMEText    #构造文本
from email.header import Header
import smtplib
def sendMail(you):user='512044050@qq'pwd='xofoxzeqmyjzcagc'#设置总的邮件对象ME=MIMEMultipart()#邮件头尾信息list=[you,'1049252083@qq', '936040416@qq']ME['From']=user#发件人ME['To']=','.join(list)#合并多个收件人l=['1049252083@qq','512044050@qq']ME['Cc']=','.join(l)#合并多个抄送人m='你好  杨小姐'#邮件主题ME['Subject']=Header(m,'utf-8')### 构造文本内容with open('D:\PROJECT\lunwen\Z公司绩效管理有效性研究.txt',encoding='utf-8') as f:res=f.read()msg=MIMEText(res,'plain','utf-8')#加上下面这行代码实现把文本内容当作附件上传,正文将没有内容# msg["Content-Disposition"] = 'attachment; filename="csdn.txt"'ME.attach(msg)#添加到邮件整体内容中#构造附件txt_file = open(r'D:\PROJECT\lunwen\“人性化”管理是企业管理的必然趋势.txt', 'rb').read()txt = MIMEText(txt_file, 'base64', 'utf-8')txt["Content-Type"] = 'application/octet-stream'#以下代码可以重命名附件为hello_world.txt发送txt["Content-Disposition"] = 'attachment; filename="red_people.txt"'ME.attach(txt)#添加到邮件整体内容中flage=Truewhile flage:try:smp=smtplib.SMTP('smtp.qq',25)smp.login(user,pwd)smp.sendmail(user,you,ME.as_string())print('邮件发送成功')breakexcept:print('邮件发送失败,尝试重新发送')break
if __name__=='__main__':sendMail('936040416@qq')```

更多推荐

python发送邮件之SMTP

本文发布于:2024-03-11 17:26:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1729497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送邮件   python   SMTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!