首页 > 编程问答 >使用 python Flask 发送邮件中的图像

使用 python Flask 发送邮件中的图像

时间:2024-07-25 06:12:52浏览次数:10  
标签:python email flask smtplib

我想发送一封包含 html 代码和图像的电子邮件

但在 gmail 中它说图像已附加,我不想要这样,我只想要电子邮件正文中的图像。

html_content=f"<img src="cid:banner" alt="" style="width:80%;">"
 msg = MIMEMultipart('related')
    html_part = MIMEText(html_content, 'html')
    msg.attach(html_part)


    with open(image_path, 'rb') as f:
        image_data = f.read()


    image_attachment = MIMEImage(image_data,'html', name='Logo')
    image_attachment.add_header('Content-ID','<banner>')  # Unique identifier for the image
    msg.attach(image_attachment)



    # Subject of E-mail
    msg['Subject'] = f"Aire Frio Maracay ❄"
    # Sender E-mail Id
    sender = '[email protected]'
    msg['From'] = sender
    # Receiver E-mail Id
    recipient = '[email protected]'
    msg['To'] = recipient
    # SMTP Server
    server = smtplib.SMTP_SSL('smtp.zoho.com', 465)
    # SMTP Server Login Credentials
    server.login(sender, 'gYDY04USz6ru')
    # Gives Send Mail Request to SMTP Server
    server.sendmail(sender, recipient, msg.as_string())
    # Quit or Logout from SMTP Server 
    server.quit()

我不想要想要这个

我只是想要这个

我尝试在youtube中搜索并询问Gemini IA,但我没有找到解决方案


The problem is that you are attaching the image as a separate entity in the email, instead of embedding it directly in the HTML.

Here's how to embed the image directly in the HTML using base64 encoding:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64

def send_email_with_image(image_path, recipient_email):
    """Sends an email with an embedded image.

    Args:
        image_path (str): The path to the image file.
        recipient_email (str): The recipient's email address.
    """

    # Read the image and encode it in base64
    with open(image_path, 'rb') as img_file:
        image_data = img_file.read()
        encoded_image = base64.b64encode(image_data).decode('utf-8')

    # Create the HTML content with the embedded image
    html_content = f"""
    <html>
    <body>
        <img src="data:image/png;base64,{encoded_image}" alt="Image" style="width:80%;">
    </body>
    </html>
    """

    # Create the email message
    msg = MIMEMultipart('related')
    msg['Subject'] = "Aire Frio Maracay ❄"
    msg['From'] = '[email protected]'
    msg['To'] = recipient_email

    # Attach the HTML part
    msg.attach(MIMEText(html_content, 'html'))

    # Send the email
    server = smtplib.SMTP_SSL('smtp.zoho.com', 465)
    server.login('[email protected]', 'gYDY04USz6ru')  # Replace with your actual password
    server.sendmail('[email protected]', recipient_email, msg.as_string())
    server.quit()

# Example usage:
image_path = 'path/to/your/image.png'  # Replace with your image path
recipient_email = '[email protected]'
send_email_with_image(image_path, recipient_email) 

Explanation:

  1. Base64 Encoding: The code reads the image file in binary mode ( 'rb' ), converts the binary data to base64 encoding, and then decodes it into a string.
  2. Embedding in HTML: The base64 encoded image string is inserted directly into the src attribute of the <img> tag within the HTML content. We use the data URI scheme ( data:image/png;base64, ) to indicate that the image data is embedded within the HTML itself.
  3. Sending the Email: The rest of the code remains similar, constructing and sending the email with the updated HTML content.

Now, the image should be displayed directly within the email body without any attachments. Make sure to:

  • Replace "path/to/your/image.png" with the actual path to your image file.
  • Verify Image Type: If your image is not a PNG, adjust the data:image/png;base64, part to match the correct MIME type (e.g., data:image/jpeg;base64, for JPEG images).

标签:python,email,flask,smtplib
From: 78790784

相关文章

  • 无法在我的 apache 服务器内对 Flask 应用程序(用于 MySQL 连接)进行远程 api 调用
    我有一个在AlmaLinux上运行的apache服务器。我有Flask代码设置来接受来自远程连接的API调用。所以我的API调用命中了Flask,然后它连接到MySQL数据库。当我尝试在服务器内部本地运行此数据库连接代码时,它工作正常。但是当我尝试通过远程API调用来访问Flask应......
  • 在 python requests modul 中,如何检查页面是否使用“POST”方法或“GET”方法
    如何使用python“requests”模块检查页面是否使用“GET”方法或“POST”方法。我期望输出为True或False,或者GET或Post预期代码:importrequestsurl=f"www.get_example.com"response=requests.get(url)ifresponse.check_get==True:print("get")你......
  • VS Code Python - 如果括号(括号、大括号等)未关闭,内联建议不起作用
    我遇到的问题是,当我在未闭合的括号或方括号“内部”开始变量名称时,VSCode将不会显示任何建议。但是,如果在键入变量名称之前闭合括号,则建议效果很好。如果我可以避免它,我宁愿不将自动完成括号关闭设置为True也不使用TabOut扩展。第一个屏幕截图显示建议在闭括号/方......
  • 在 Azure 上部署代码时使用 Python 的多处理模块是否有意义?
    我们的团队在Azure机器学习(AML)上部署了一个Python脚本来处理存储在Azure存储帐户上的文件。我们的管道由一个ForEach活动组成,该活动调用每个或列出的文件的Python脚本。从Azure数据工厂(ADF)运行它会触发多个单独的管道同时运行......
  • 我已成功安装 pypdf2 但无法将其导入到我的 python 文件中
    我已经成功安装了pypdf2模块,但在导入它时,我发现该模块丢失了。我尝试使用fromPyPDF2importPdfReader导入,但它不起作用此问题的各种解决方案是什么?在尝试导入PyPDF2时遇到问题。以下是可能导致此问题的一些常见原因和解决方案:安......
  • Python3打开图片时请求ConnectionResetError(10054)
    我试图从'http://xxx.jpg'之类的网站下载图片。代码:headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/66.0.3359.139Safari/537.36'}url='http://xxx.jpg'resp......
  • Jupyter Notebook 环境中的 Python 版本不匹配
    我遇到Jupyter笔记本启动横幅中报告的Python版本与我在笔记本中查询python--version时显示的版本之间的差异。启动横幅指示Python3.11.9,但是当我运行!python--version时,它返回Python3.11.7。我所做的步骤:basecondahas3.11.7versio......
  • Python XML 解析:字符串中的“<”被阻塞
    我有一个使用ET.XMLParser来解析CppCheckXML报告文件的Python模块。当尝试解析字符串中包含“<”的XML元素中的属性之一时,它会令人窒息,它会将其解释为格式错误的XML,例如:<errormsg="Includefile<iostream>notfound.">(注意字符和“iostream”之间的空格必须放......
  • 任意几行代码要成为Python中的函数需要什么?
    我正在上一门计算机科学课,我的任务是创建一个程序来实现一个带有参数的函数。我的老师告诉我,下面的代码不是一个函数,这让我很困惑,对于将某些代码行归类为“函数”所需的条件,我感到很困惑。defgame(numbers,max_turns,pfl,tgl):turns=0flag=Falseprint("You......
  • 如何使用 Python 创建新的 Azure 订阅?
    我正在尝试使用PythonSDK以编程方式创建新的Azure订阅。我发现的对AzurePythonSDK的唯一引用是这个这是我最终得到的结果:importazure.mgmt.billingimportazure.mgmt.subscriptioncreds=AzureCliCredential()client_name='test'defcreat......