How to add sender name before sender address in python email script
Stefan Bogdanescu
Founder & Senior Architect
How to Add Sender Name Before Sender Address in Python Email Scripts
Sending emails programmatically often involves dealing with MIME structures and HTTP protocols, which can be tricky when you need to customize the sender identity beyond just the raw email address. When you send an email via a simple smtplib script, the recipient's inbox primarily relies on the From: header for identification. However, if you want a custom display name—especially one that renders nicely in HTML (like your desired <a> tag)—you need to manage both the SMTP headers and the message body content simultaneously.
This guide will walk you through the developer-centric approach to correctly structuring your Python email messages so that the sender's name precedes their address, allowing for rich display formatting.
The Challenge: Headers vs. Content
The core difficulty lies in understanding the difference between what the SMTP server processes (the raw headers) and what the recipient client renders (the message body). While you set the From: header to define the sender, the display name often needs to be explicitly embedded within the HTML content of the email itself.
Simply setting a custom name in the header might work for some older systems, but modern email clients prioritize the content inside the HTML payload when rendering links and text.
The Solution: Constructing Richer MIME Messages
To achieve the desired result—displaying a sender name before an address formatted as a link—we must construct the message body (specifically the HTML part) to include this information explicitly. We will leverage the MIMEMultipart structure you started with, ensuring both plain text and HTML versions are present.
Here is how we modify your Python script to inject the sender name into the HTML content:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# --- Configuration ---
addr_to = 'user@outlook.com'
addr_from = 'user@aol.com'
smtp_server = 'smtp.aol.com'
smtp_user = 'user@aol.com'
smtp_pass = 'pass'
# Define the desired sender name
sender_name = "John Developer"
# Construct email container
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
# Set the From header to include the display name (RFC compliant format)
msg['From'] = f'{sender_name} <{addr_from}>'
msg['Subject'] = 'Test Email with Custom Sender'
# --- Constructing the HTML Body with Custom Link ---
html_content = f"""
<html>
<head>
<meta charset="UTF-8">
<style>
body {{ font-family: Arial, sans-serif; }}
</style>
</head>
<body>
<h1>Email Notification</h1>
<p>Dear Recipient,</p>
<p>This message is from: <a href="https://i.sstatic.net/HDEXx.jpg" rel="noreferrer">{sender_name}</a>.</p>
<p>Please review the details below.</p>
</body>
</html>
"""
# Create the body of the message (plain-text and an HTML version).
text = "This is a plain text test message."
html = html_content
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container. HTML is preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via an SMTP server
try:
s = smtplib.SMTP(smtp_server)
s.login(smtp_user, smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
Developer Insights and Best Practices
Notice how we constructed the msg['From'] header using an f-string to combine the name and address, which is a standard way to adhere to RFC standards for sender identification. More importantly, we embedded this exact information—the custom link—directly into the HTML payload (html_content). This ensures that when the email client parses the HTML, it sees the desired structure immediately, regardless of slight variations in how the underlying MTA handles header parsing.
When building complex messaging systems, think about separation of concerns. While Python's smtplib is functional, for more robust and feature-rich email handling, especially when dealing with high volumes or complex personalization (like dynamic sender names based on database lookups), exploring frameworks can be beneficial. For instance, while this example uses raw Python, modern application development often relies on well-structured services, much like how packages in the Laravel ecosystem are designed for modularity.
Always validate your credentials and SMTP settings before running production scripts, as demonstrated by ensuring robust error handling (like the try...except block above).
Conclusion
By combining correct header manipulation with rich HTML content construction, you gain full control over how your email is presented to the recipient. The key takeaway is that for dynamic display elements like sender names and links, embed the finalized, styled content within the MIME message body rather than relying solely on the raw header fields. Mastering this balance between protocol structure and presentation logic is crucial for any developer working with email systems.
Note: Blog content is currently available in English.