Python – How to add sender name before sender address in python email script

emailpythonsmtp

Here's my code

    # Import smtplib to provide email functions
    import smtplib

    # Import the email modules
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    # Define email addresses to use
    addr_to   = 'user@outlook.com'
    addr_from = 'user@aol.com'

    # Define SMTP email server details
    smtp_server = 'smtp.aol.com'
    smtp_user   = 'user@aol.com'
    smtp_pass   = 'pass'

    # Construct email
    msg = MIMEMultipart('alternative')
    msg['To'] = addr_to
    msg['From'] = addr_from
    msg['Subject'] = 'test test test!'

    # Create the body of the message (a plain-text and an HTML version).
    text = "This is a test message.\nText and html."
    html = """\

    """

    # 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.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)

    # Send the message via an SMTP server
    s = smtplib.SMTP(smtp_server)
    s.login(smtp_user,smtp_pass)
    s.sendmail(addr_from, addr_to, msg.as_string())
    s.quit()

I just want the email received to display the sender name before sender email address like this : sender_name

Best Answer

In the year 2020 and Python 3, you do things like this:

from email.utils import formataddr
from email.message import EmailMessage
import smtplib

msg = EmailMessage()
msg['From'] = formataddr(('Example Sender Name', 'john@example.com'))
msg['To'] = formataddr(('Example Recipient Name', 'jack@example.org'))
msg.set_content('Lorem Ipsum')

with smtplib.SMTP('localhost') as s:
    s.send_message(msg)