Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

email

smtp

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   = '[email protected]'
addr_from = '[email protected]'
 
# Define SMTP email server details
smtp_server = 'smtp.aol.com'
smtp_user   = '[email protected]'
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

like image 600
mrassili Avatar asked Sep 08 '17 03:09

mrassili


People also ask

What is MIMEMultipart in Python?

MIMEMultipart is for saying "I have more than one part", and then listing the parts - you do that if you have attachments, you also do it to provide alternative versions of the same content (e.g. a plain text version plus an HTML version)

How do I use Smtplib in Python 3?

Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon. host − This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com.

How do you send an email to multiple recipients in Python?

sendmail() function. In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.


1 Answers

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', '[email protected]'))
msg['To'] = formataddr(('Example Recipient Name', '[email protected]'))
msg.set_content('Lorem Ipsum')

with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
like image 195
Danila Vershinin Avatar answered Sep 20 '22 20:09

Danila Vershinin