简体   繁体   English

在 Python3 中使用 SMTPLIB - 尝试发送 email 时出现(501)“语法错误 - 行太长”错误

[英]Using SMTPLIB with Python3 - Getting (501) "Syntax error - line too long" Error When trying to send the email

Here is the syntax I use to build an email, the email itself will send unless I add an attachment, then I get the error.这是我用来构建 email 的语法,除非我添加附件,否则 email 本身将发送,然后我收到错误消息。

Or if my HTML is too long, I'll get the error:或者如果我的 HTML 太长,我会得到错误:

# MSG building
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(email_text, "plain"))
msg.attach(MIMEText(email_html, "html"))

msg["To"] = to_email
msg["From"] = from_email
msg["Subject"] = subject
msg["Date"] = formatdate()
msg["Message-ID"] = make_msgid(domain=sender_domain)

with open(attachment_dir, 'rb') as f:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(f.read())
    
    # Encode to Base64                
    encoders.encode_base64(part)
    
    # Set mail headers
    part.add_header(
        "Content-Disposition", "attachment", filename=attachment_name
        )
    
    msg.attach(part)
    
# Python 3 libraries expect bytes.
msg_data = msg.as_bytes()

# Create secure connection with server and send email
context = ssl.create_default_context()

with smtplib.SMTP_SSL("smtp.ionos.co.uk", 465, context=context) as mailserver:
    mailserver.login(from_email, from_password)
    mailserver.sendmail(from_email, to_email, msg_data)

Here is the Traceback I'm getting (It's a standard line too long error):这是我得到的 Traceback(这是一个标准行太长错误):

Traceback (most recent call last):
  File "/home/server/repos/mailsender/run.py", line 33, in <module>
    email.send()
  File "/home/server/repos/mailsender/main.py", line 139, in send
    mailserver.sendmail(from_email, to_email, msg_data)
  File "/usr/lib/python3.9/smtplib.py", line 892, in sendmail
    raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (501, b'Syntax error - line too long')

Syntactically, how do I avoid this- I understand the error message, but how can I get around that and fix it in Python3从语法上讲,我该如何避免这种情况 - 我理解错误消息,但我怎样才能解决这个问题并在 Python3 中修复它

Thanks in advance提前致谢

Here is the Image I tried to attach: https://i.stack.imgur.com/QTprF.jpg这是我尝试附加的图片: https://i.stack.imgur.com/QTprF.jpg

It's not even 1MB in size.它的大小甚至不到 1MB。

After spending 5 days trying to solve it, and 4 weeks with it causing issues in production...在花了 5 天的时间尝试解决它,并在 4 周的时间里导致了生产中的问题......

The answer:答案:

msg_data = msg.as_bytes()

This needed to be这需要

msg_data = msg.as_string()

I did need to convert it to bytes when pushing it into the outbox though.不过,在将其推入发件箱时,我确实需要将其转换为字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM