2026-07-15

add sender's name in the from field of the email in python

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

add sender's name in the from field of the email in python

Mastering Email Headers: How to Add Sender Names Correctly in Python SMTP

Sending emails programmatically using Python's smtplib is a powerful skill. However, dealing with email headers—specifically the From field—often introduces unexpected complications regarding display names and sender identities. As a senior developer, I've seen many developers encounter this exact issue where the displayed "From" name appears corrupted or includes machine hostnames, leading to confusion upon receipt.

This post will diagnose why you are seeing these strange details and provide robust solutions to ensure your emails are delivered with the correct sender information. We will move beyond simply setting a string and dive into the structure of email standards.

The Mystery of Corrupted 'From' Fields

You are attempting to set the sender information using msg['From'] = "XYZ ABC". While this works for basic addressing, the strange output you receive (e.g., including <machine-hostname-appearing-here>) points to a deeper issue related to how the underlying Mail Transfer Agent (MTA) or the receiving mail server interprets the envelope versus the header information.

In simple terms:

  1. Envelope Sender: This is the technical address used for routing (often derived from the SMTP session).
  2. Header Sender (From): This is what the recipient sees in their inbox, which includes the display name and email address.

When you use a basic sendmail approach without proper authentication or full SMTP negotiation, the receiving system often defaults to using the machine's hostname as part of the sender identity if it cannot confidently parse the provided header data, leading to those garbled results you observed.

The Developer Solution: Structuring Headers Properly

To fix this, we need to ensure that the information we place into the message object adheres strictly to RFC standards for email headers. Simply setting the From field is often insufficient; we must define both the display name and the actual address clearly within the header structure.

The most reliable way to handle this in Python is to construct the full header string manually or use a library function that handles the MIME structure explicitly, rather than relying solely on simple dictionary assignment for complex fields like From.

Correcting the Python Implementation

Instead of assigning a plain string to msg['From'], we will construct the complete From header line precisely as required. This ensures that the display name is correctly separated from the email address.

Here is the corrected approach:

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'
display_name = 'XYZ ABC'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    
    # --- FIX APPLIED HERE ---
    # Construct the From header explicitly with Name <email@domain.com> format
    msg['From'] = f'{display_name} <{sender}>'
    # ------------------------
    
    msg['To'] = recipients
    
    try:
        s = smtplib.SMTP('localhost')
        # Note: For real-world sending, you must use proper authentication (s.login(user, password))
        s.sendmail(sender, receiver, msg.as_string())
        print("Successfully sent email")
    except Exception as e: # Using a generic exception for demonstration; handle specific SMTPException in production
        print(f"Error: unable to send email - {e}")
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
"""

mail_me(cont,['xyz@xyzcom'])

Best Practices for Robust Email Sending

When building robust communication systems, especially when dealing with email infrastructure, attention to detail is paramount. This principle of correct data structuring mirrors the reliability expected in modern application development, much like the principles taught in frameworks like Laravel, where clear contracts between components are essential for stability.

  1. Use Proper SMTP Authentication: Never rely on local testing setups for production. Always configure your script to use secure SMTP credentials (s.login(username, password)) when connecting to external services (like Gmail or SendGrid).
  2. MIME Structure is King: Treat email headers as structured data. Use the email library (or related tools if you are building complex MIME messages) to ensure that all parts of the message (headers, body, attachments) are correctly formatted according to RFC standards.
  3. Inspect Headers: If problems persist, use an external tool or a simple script to inspect the raw email headers received by your mail server. This helps determine exactly where the parsing error is occurring—whether it’s in the sending process or the receiving agent.

Conclusion

The issue you faced stems from a mismatch between the loose string assignment and the strict requirements of email header formatting. By explicitly constructing the From header using the standard Name <email@domain.com> format, you provide the mail system with unambiguous instructions. This practice ensures that your sender's name is displayed correctly to recipients, regardless of the underlying server configuration. Implementing these disciplined coding practices will make your email automation reliable and professional.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.