鱼C论坛

 找回密码
 立即注册
查看: 839|回复: 5

[已解决]smtplib发送邮件

[复制链接]
发表于 2023-7-17 21:23:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
m_text = MIMEText(text, 'html', 'utf-8')这里html改成plain,正文就没法显示图片,html的话,附件的xlsx文件打开内容就是乱码。
求助,怎么让正文显示图片,附件xlsx也正常显示。
import smtplib
from pathlib import Path
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 1.发送人账号
sendAddress = '****@***.****.com'
# 2.发送人授权码
password = '****'
#(乱写的 要去QQ邮箱找自己的哦)

# 1定义一个可以添加正文和附件的邮件消息对象
msg = MIMEMultipart()
#
To = ['13973519903@139.com']
# Cc = ['13975789908@139.com', '13787775557@139.com']
Cc = []
reciver = To + Cc

msg['From'] = sendAddress
msg['To'] = ','.join(To)
msg['Cc'] = ','.join(Cc)
msg['subject'] = '邮件标题'

text = f"""邮件正文
<img src="cid:0">
"""
# html文本引入id为0的图片

m_text = MIMEText(text, 'html', 'utf-8')
#这里html改成plain,正文就没法显示图片,html的话,附件的xlsx文件打开内容就是乱码

msg.attach(m_text)


# 邮件加入图片
m_img = MIMEBase('image', 'jpg')
m_img.add_header('Content-Disposition', 'attachment')
m_img.add_header('Content-ID', '<0>')   # 设置图片id为0
f = open(r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.png", "rb")   # 读取本地图片
m_img.set_payload(f.read())
encoders.encode_base64(m_img)
msg.attach(m_img)

# 添加excel附件

# xlsx = MIMEApplication(open(r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.xlsx", 'rb').read())  # 打开Excel,读取Excel文件
xlsx = MIMEText(open(r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.xlsx", 'rb').read(), 'base64', 'utf-8')
# xlsx["Content-Type"] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'       # 设置内容类型
xlsx["Content-Type"] = 'application/octet-stream'
# xlsx['Content-Disposition'] = 'attachment;filename="2023年07月17日精品企宽重复投诉率日通报.xlsx"'
xlsx.add_header('Content-Disposition', 'attachment', filename="2023年07月17日精品企宽重复投诉率日通报.xlsx")
# encoders.encode_base64(xlsx)
msg.attach(xlsx)

# 3.连通服务器
# 465端口就是
server = smtplib.SMTP_SSL('****.*****.com', 465)
print(server)
# 4.登录
loginResult = server.login(sendAddress, password)
print(loginResult)
# (235, b'Authentication successful') 这样子的代表你登陆成功了
# 235响应成功状态码

# 发送邮件

try:
    server.sendmail(sendAddress, reciver, msg.as_string())
    print("发送成功")
    email = '成功了'
    server.quit()
except:
    print("发送失败")
    email = ''
    server.quit()

最佳答案
2023-7-17 21:23:57
在使用 smtplib 发送邮件时,可以通过嵌入图片作为正文的方式来显示图片,同时保证附件的正常显示。以下是修改后的代码示例:
import smtplibfrom pathlib import Pathfrom email.mime.application import MIMEApplicationfrom email.mime.base import MIMEBasefrom email import encodersfrom email.mime.image import MIMEImagefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Header# 1. 发送人账号sendAddress = '****@***.****.com'# 2. 发送人授权码password = '****'  # (请替换为自己的授权码)# 收件人列表To = ['13973519903@139.com']Cc = []reciver = To + Cc# 创建邮件消息对象msg = MIMEMultipart()msg['From'] = sendAddressmsg['To'] = ','.join(To)msg['Cc'] = ','.join(Cc)msg['Subject'] = '邮件标题'# 添加邮件正文text = """<html><body><p>邮件正文</p><img src="cid:0"></body></html>"""m_text = MIMEText(text, 'html', 'utf-8')msg.attach(m_text)# 添加图片附件with open(r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.png", "rb") as f:    m_img = MIMEImage(f.read())    m_img.add_header('Content-ID', '<0>')  # 设置图片id为0    msg.attach(m_img)# 添加Excel附件xlsx_path = r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.xlsx"xlsx = MIMEApplication(open(xlsx_path, 'rb').read())xlsx.add_header('Content-Disposition', 'attachment', filename=Path(xlsx_path).name)msg.attach(xlsx)# 连接邮件服务器并发送邮件try:    server = smtplib.SMTP_SSL('****.*****.com', 465)  # 这里请替换为邮件服务器的地址    loginResult = server.login(sendAddress, password)    print(loginResult)  # (235, b'Authentication successful')    server.sendmail(sendAddress, reciver, msg.as_string())    server.quit()    print("发送成功")except Exception as e:    print("发送失败:", e)
请注意替换 sendAddresspassword 和邮件服务器地址为你自己的信息,并确保图片和附件文件的路径正确。同时,邮件正文中的图片引用时,使用了 cid:0,需要根据实际情况进行调整。

如果还有其他问题,请随时提问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-7-17 21:23:57 | 显示全部楼层    本楼为最佳答案   
在使用 smtplib 发送邮件时,可以通过嵌入图片作为正文的方式来显示图片,同时保证附件的正常显示。以下是修改后的代码示例:
import smtplibfrom pathlib import Pathfrom email.mime.application import MIMEApplicationfrom email.mime.base import MIMEBasefrom email import encodersfrom email.mime.image import MIMEImagefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Header# 1. 发送人账号sendAddress = '****@***.****.com'# 2. 发送人授权码password = '****'  # (请替换为自己的授权码)# 收件人列表To = ['13973519903@139.com']Cc = []reciver = To + Cc# 创建邮件消息对象msg = MIMEMultipart()msg['From'] = sendAddressmsg['To'] = ','.join(To)msg['Cc'] = ','.join(Cc)msg['Subject'] = '邮件标题'# 添加邮件正文text = """<html><body><p>邮件正文</p><img src="cid:0"></body></html>"""m_text = MIMEText(text, 'html', 'utf-8')msg.attach(m_text)# 添加图片附件with open(r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.png", "rb") as f:    m_img = MIMEImage(f.read())    m_img.add_header('Content-ID', '<0>')  # 设置图片id为0    msg.attach(m_img)# 添加Excel附件xlsx_path = r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.xlsx"xlsx = MIMEApplication(open(xlsx_path, 'rb').read())xlsx.add_header('Content-Disposition', 'attachment', filename=Path(xlsx_path).name)msg.attach(xlsx)# 连接邮件服务器并发送邮件try:    server = smtplib.SMTP_SSL('****.*****.com', 465)  # 这里请替换为邮件服务器的地址    loginResult = server.login(sendAddress, password)    print(loginResult)  # (235, b'Authentication successful')    server.sendmail(sendAddress, reciver, msg.as_string())    server.quit()    print("发送成功")except Exception as e:    print("发送失败:", e)
请注意替换 sendAddresspassword 和邮件服务器地址为你自己的信息,并确保图片和附件文件的路径正确。同时,邮件正文中的图片引用时,使用了 cid:0,需要根据实际情况进行调整。

如果还有其他问题,请随时提问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-7-17 21:24:00 | 显示全部楼层
在您的问题中,出现了当您尝试在邮件正文中插入图片并附带Excel文件作为附件时,图片可以正常显示,但是Excel文件会显示为乱码的问题。

根据您提供的代码,我发现您在添加Excel文件作为附件的方法存在问题。您应该使用 MIMEApplication 而不是 MIMEText 来处理Excel文件。您应该使用下面的代码来创建并附加Excel文件:
xlsx_path = r"C:\Users\Nothing\Downloads\2023年07月17日精品企宽重复投诉率日通报.xlsx"with open(xlsx_path, "rb") as f:    xlsx = MIMEApplication(f.read())    # 添加邮件头信息    xlsx.add_header('Content-Disposition', 'attachment', filename="2023年07月17日精品企宽重复投诉率日通报.xlsx")    msg.attach(xlsx)
在上述代码中, MIMEApplication 类是用于处理不同类型的文件(例如PDF,Excel,Word等)的,而 MIMEText 主要是用于处理文本内容,例如邮件的正文。当你用 MIMEText 来读取和编码Excel文件时,这个Excel文件就会变成一个文本文件,这就是为什么你看到的Excel文件内容是乱码的原因。

总的来说,你应该使用正确的MIME类型来处理你的邮件内容和附件, MIMEText 用于处理文本内容, MIMEImage 用于处理图片,而 MIMEApplication 用于处理其他类型的文件,例如PDF,Excel等。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-7-17 21:27:29 | 显示全部楼层
isdkz 发表于 2023-7-17 21:24
在您的问题中,出现了当您尝试在邮件正文中插入图片并附带Excel文件作为附件时,图片可以正常显示,但是Exc ...

我用MIMEApplication试过,也不行。
我代码里面有对应的语句,只不过被我注释掉了,换成MIMEText,效果是一样的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-7-17 21:31:27 | 显示全部楼层
陶远航 发表于 2023-7-17 21:23
在使用 smtplib 发送邮件时,可以通过嵌入图片作为正文的方式来显示图片,同时保证附件的正常显示。以下是 ...

测试了,成功了,谢谢!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-7-17 21:36:05 | 显示全部楼层
nothingwnw 发表于 2023-7-17 21:27
我用MIMEApplication试过,也不行。
我代码里面有对应的语句,只不过被我注释掉了,换成MIMEText,效果 ...

是因为你用Application的时候没用 add_header 吧
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 11:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表