[SOLVED] Using SMTPLIB with Python3 – Getting (501) “Syntax error – line too long” Error When trying to send the email

Issue

This Content is from Stack Overflow. Question asked by Mr Growbot

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.

Or if my HTML is too long, I’ll get the error:

# 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 (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

Thanks in advance

Here is the Image I tried to attach: https://i.stack.imgur.com/QTprF.jpg

It’s not even 1MB in size.



Solution

After spending 5 days trying to solve it, and 4 weeks with it causing issues in production…

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.


This Question was asked in StackOverflow by Mr Growbot and Answered by Mr Growbot It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?