Python3 SMTP发送邮件
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
Python创建 SMTP 对象语法如下
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
参数说明:
- host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:runoob.com,这个是可选参数。
- port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下SMTP端口号为25。
- local_hostname: 如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。
Python SMTP对象使用sendmail方法发送邮件,语法如下:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
参数说明:
- from_addr: 邮件发送者地址。
- to_addrs: 字符串列表,邮件发送地址。
- msg: 发送消息
这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
mail_host="smtp.XXX.com" #设置服务器
mail_user="XXXX" #用户名
mail_pass="XXXXXX" #口令
sender = 'from@runoob.com'
receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')
message['To'] = Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号,连接邮件服务器
smtpObj.login(mail_user,mail_pass) # 通过用户名和授权码进行登录
smtpObj.sendmail(sender, receivers, message.as_string())
print ("邮件发送成功")
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
我们使用三个引号来设置邮件信息,标准邮件需要三个头部信息: From, To, 和 Subject ,每个信息直接使用空行分割。
我们通过实例化 smtplib 模块的 SMTP 对象 smtpObj 来连接到 SMTP 访问,并使用 sendmail 方法来发送信息。
Python 发送带附件的邮件
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = 'from@runoob.com'
receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("菜鸟教程", 'utf-8')
message['To'] = Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
#邮件正文内容
message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8'))
# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)
# 构造附件2,传送当前目录下的 runoob.txt 文件
att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
message.attach(att2)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print ("邮件发送成功")
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
核心代码
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 邮件头部
email = MIMEMultipart()
email['From']= 'hsdhsdfhscd@126.com'
email['To'] = 'ajjdjs@qq.com;kdksdkd@126.com'
email['Cc'] = 'ajjdjs@qq.com' # 抄送
email['Subject'] = '111111' # 主题
# 邮件正文
message = MIMEText('...','plain','utf-8')
email.attach(message)
# 邮件附件
attachment = MIMEText('...','base64','utf-8')
attachment['content-type'] ='application/octet-stream'
attachment['content-disposition'] = 'attachment;filename = "..."'
email.attach(attachment)
# 发送邮件
smtp =smtplib.SMTP_SSL(host = 'smtp.126.com',port=465) # 建立连接
smtp.login('hsdhsdfhscd@126.com','...') # 登录授权
smtp.sendmail('hsdhsdfhscd@126.com',['ajjdjs@qq.com','kdksdkd@126.com'],email.as_string()) # 指定发件人,收件人
下载文件+归档压缩+发送邮件
归档:多个文件合到一个文件中
压缩:大文件变成小文件 ---> 无损压缩/有损压缩
import os.path
from shlex import quote
import requests
import shutil # 封装了高级的文件操作函数
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
HOST='smtp.126.com'
PORT=465
USER='hsdhsdfhscd@126.com'
PASS='...'
# 发送邮件
def send_email(from_user,to_user,subject='',content='',filenames=[]):
# 邮件头部
email = MIMEMultipart()
email['From'] = from_user
email['To'] =';'.join(to_user)
email['Subject'] = subject # 主题
# 邮件正文
message = MIMEText(content, 'plain', 'utf-8')
email.attach(message)
# 邮件附件
for filename in filenames:
with open(filename,'rb')as file:
pos = filename.rfind('/')
display_filename = filename[pos +1:] if pos >=0 else filename
display_filename = quote(display_filename)
attachment = MIMEText(file.read(), 'base64', 'utf-8')
attachment['content-type'] = 'application/octet-stream'
attachment['content-disposition'] = f'attachment;filename ={display_filename}'
email.attach(attachment)
# 发送邮件
smtp = smtplib.SMTP_SSL(HOST, PORT) # 建立连接
smtp.login(USER, PASS) # 登录授权
smtp.sendmail(from_user, to_user, email.as_string()) # 指定发件人,收件人
# 下载图片
def download_picture(path,url):
filename = url[url.rfind('/')+1:]
resp = requests.get(url)
with open(f'{path}{filename}','wb') as file:
file.write(resp.content)
def main():
# 如果指定文件不存在,就创建该文件
if not os.path.exists('images'):
os.makedirs('images')
resp = requests.get('https://image.so.com/zjl?ch=beauty&sn=30')
beauty_list = resp.json()['list']
for beauty_dict in beauty_list:
print(beauty_dict)
picture_url = beauty_dict['qhimg_url']
download_picture('images/', picture_url)
# 生成归档文件(带压缩):生成mm.zip文件
shutil.make_archive('mm','zip','images')
send_email('',[],'','',['mm.zip'])
if __name__ == '__main__':
main()