Here's a simple test that demonstrates the problem I'm seeing:
import smtplib
from email.message import EmailMessage
my_addr = 'my_email@my_domain.com'
str = ''
for i in range(500):
str += f'{i}: <a href="https://google.com">https://google.com</a><br>'
msg = EmailMessage()
msg.set_content('')
msg.add_alternative(str, subtype='html')
msg['Subject'] = 'html test'
msg['From'] = my_addr
msg.add_header('reply-to', my_addr)
msg['To'] = my_addr
with smtplib.SMTP('localhost', timeout=30) as smtp_server:
smtp_server.send_message(msg)
The resulting email seems to "break" about every 1000 bytes in the input html. This length includes any tags in the HTML string. The received email looks something like this:
I've tried different SMTP servers with different message length limits, but all were set to 10M or higher, so I doubt this had any effect. Also, I receive no error codes or exceptions. Everything sends cleanly. smtplib just seems to break up the message somehow.
Any idea what the problem is or how to correct this?
Problem:
It is a result of line line length limit imposed by SMTP servers.
It causes breaking too long lines.
Solution:
Insert line break characters into your html string.
for i in range(500):
str += f'{i}: <a href="https://google.com">https://google.com</a><br>\n'
tidy
program may be used to break long HTML lines (among other things).
Links:
Is there an accepted maximum line length for SMTP header fields?