Search code examples
pythonpython-3.xsmtplibemail-headers

How to overcome 988 char limitation in email header?


I am trying to send emails to a large number of individuals (100+), but a newline is being introduced after the 988th character, which interrupts the email string, causing an "undeliverable" error.

I am relatively new to coding in general but have managed to piece together some snippets of code from some online research. I have tried to utilize a Header object instead but I received the same result.

i.e.:

from email.header import Header
msg['To'] = str(Header(','.join(list_of_emails)))

from the limited information that I was able to find, I gather that the header must be folded to comply with RC 2822 formats but I am unaware on how to do so.

import smtplib
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg = MIMEMultipart()
msg['From'] = me
msg['To'] = ','.join(['john@example.com', 'mary@example.com', 
                   ..., 'mike@example'])
msg['Subject'] = subject

body = 'enter text here'

msg.attach(MIMEText(body,'plain'))

filename = 'abc123.xlsx'   
attachment = open('C:\Users\......', "rb")    

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
attachment.close()

encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename={filename}")

msg.attach(part)
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(user, password)
server.send_message(msg)
server.quit()

The block of code does exactly what I expect it to: send an email including appropriate headers, body, and attachment. I have no issues that arise until I start including a large amount of recipients under msg['To']. For example if use a list containing 100+ emails, some of them are interrupted with a line break and displays as such, 'bobsmith@ex ample.com' I believe I am encountering this issue due to the character limitations in 1 line however I do not know how I can overcome this problem.


Solution

  • Your assumption that the line msg['To'] = str(Header(','.join(list_of_emails))) is the problem is correct. The line wrapping is automatic (you don't need to convert to str manually, or use a Header). However, the line wrapping relies on spaces, not commas, as delimiters. So without any word breaks, your line gets split every 988 characters. With word breaks, you are fine as long as no address exceeds 988 characters. To insert spaces, replace the problematic line with

    msg['To'] = Header(', '.join(list_of_emails))
    

    or just

    msg['To'] = ', '.join(list_of_emails)
    

    Keep in mind that you are using a legacy API to begin with.