Sending long emails in Python

How to send mail using SMTPlib and Python with many line bodies

  • Table of contents

If you are sending long emails using Python it is best to use MIMEText when building your message. Here is an example:

First setup your libraries

import smtplib, ssl
import os
# get an api key at
import mailslurp_client
from smtplib import SMTP
from mailslurp_client import CreateInboxDto

api_key = os.environ.get('API_KEY')
assert api_key is not None

# create a mailslurp configuration
configuration = mailslurp_client.Configuration()
configuration.api_key['x-api-key'] = api_key
context = ssl.create_default_context()

Code example

from email.mime.text import MIMEText

with mailslurp_client.ApiClient(configuration) as api_client:
    inbox_controller = mailslurp_client.InboxControllerApi(api_client)
    inbox1 = inbox_controller.create_inbox_with_options(CreateInboxDto(inbox_type="SMTP_INBOX"))
    inbox2 = inbox_controller.create_inbox_with_options(CreateInboxDto(inbox_type="SMTP_INBOX"))
    smtp_access = inbox_controller.get_imap_smtp_access(

    # create long message
    text = ""
    for i in range(1, 42):
        text += "This is line {}\n".format(i)

    context = ssl.create_default_context()
        server = smtplib.SMTP(smtp_access.secure_smtp_server_host, smtp_access.secure_smtp_server_port)
        server.login(smtp_access.smtp_username, smtp_access.smtp_password)
        # recipients
        subject = "A message with a 41-line body"
        from_address = inbox1.email_address
        to_address = inbox2.email_address
        # send message
        message = MIMEText(text)
        # Set the email subject and 'From' and 'To' headers
        message["Subject"] = subject
        message["From"] = from_address
        message["To"] = to_address
        server.sendmail(from_address, to_address, message.as_string())

        # now fetch email from inbox2
        wait_for_controller = mailslurp_client.WaitForControllerApi(api_client)
        email = wait_for_controller.wait_for_latest_email(
        assert email.subject == subject

        # assert sent all lines
        assert "This is line 41" in email.body