我正在尝试将图像附加到我的电子邮件发件人 python

Im trying to attach an image to my email sender written python

这是我的代码

import sys
import smtplib
import imghdr
from  email.message import EmailMessage
from tkfilebrowser import askopenfilename
from email.mime.base import MIMEBase
from email.encoders import encode_base64
from email import encoders

def send():
    msg = EmailMessage()
    msg['Subject'] = body
    msg['From'] = 'sender@gmail.com'
    msg['To'] = 'receiver@gmail.com'

它运行良好,直到我在下面添加它以附加图像

    with open('DSC_0020.jpg', 'rb') as f:
        mime =  MIMEBase('image', 'jpg', filename="DSC_0020.jpg")
        mime.add_header('Content-Dispotion', 'attachment', filename="DSC_0020.jpg")
        mime.add_header('X-Attachment-Id', '0')
        mime.add_header('Content-ID', '<0>')
        mime.set_payload(f.read())
        encoders.encode_base64(mime)
        mime.attach(mime)
                      
    msg.set_content('This is a plain text email')
    msg.add_alternative("""\
        <DOCTYPE html>
        <html>
            <body>
                <h1 style="color:gray;"> This is an HTML Email! </h1>
                <img src="body">
            </body>
        </html>
        """, subtype='html')

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login('sender51@gmail.com', 'password')
        smtp.send_message(msg)

这是我得到的错误,谁能告诉我我做错了什么

文件“C:\Users\my name\AppData\Local\Programs\Python\Python38\lib\email\message.py”,第 210 行,在附件中 raise TypeError("Attach is not valid on a message with a" TypeError:附加在具有非多部分有效负载的消息上无效

电子邮件的主要部分应为 MIMEMUltipart 类型,然后文本内容应为 MIMEText 类型,如下所示:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# and, of course, other imports

msg = MIMEMultipart('alternative') # to support alternatives
msg['Subject'] = body
msg['From'] = 'sender@gmail.com'
msg['To'] = 'receiver@gmail.com'

with open('DSC_0020.jpg', 'rb') as f:
    mime =  MIMEBase('image', 'jpg', filename="DSC_0020.jpg")
    mime.add_header('Content-Disposition', 'attachment', filename="DSC_0020.jpg") # corrected header
    mime.add_header('X-Attachment-Id', '0')
    mime.add_header('Content-ID', '<0>')
    mime.set_payload(f.read())
    encode_base64(mime) # improved statement (you can now get rid of following import: from email import encoders)
    msg.attach(mime) # corrected statement

# Attach the plain text as first alternative
msg.attach(MIMEText('This is a plain text email', 'plain'))
# Attach html text as second alternative
msg.attach(MIMEText("""\
    <DOCTYPE html>
    <html>
        <body>
            <h1 style="color:gray;"> This is an HTML Email! </h1>
            <img src="body">
        </body>
    </html>
    """, 'html'))

您的文件处理块中有一些错误,我已尝试更正。可能还有其他我没有注意到。