Changing the name that is displayed when sending an email through python?
Question:
I am going to send an email to a bunch of people listed in a .csv
containing a html image using python. I have got this to work fine using the code snippet below, however when it has sent, it appears in the recipient’s inbox with the full email ("****@gmail.com") and I would like for it to just say my name, for example "dezza". I have already changed the name on gmail (and when I send anything from the gmail client it does appear as just "dezza") but it doesnt roll over to python. Is there any way to do this?
Please let me know if there is anything unclear in my question. Thanks!
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Test 1"
html = f"""
<html>
<body>
<img src="cid:Mailtrapimage">
</body>
</html>
"""
part = MIMEText(html, "html")
msg.attach(part)
with open(imgfile, 'rb') as fp:
img = MIMEImage(fp.read())
fp.close
img.add_header('Content-ID', '<Mailtrapimage>')
msg.attach(img)
# Send the email (this example assumes SMTP authentication is required)
s = smtplib.SMTP('smtp.gmail.com', 587) # creates SMTP session
s.starttls() # start TLS for security
s.login(fromaddr, password)
s.send_message(msg)
s.quit()
Answers:
Just like that
fromaddr = "dezza <****@gmail.com>"
You can do it with formataddr
function:
import email.utils
msg["From"] = email.utils.formataddr((sender_name, sender_email))
in your example it will be:
msg["From"] = email.utils.formataddr(('dezza', '****@gmail.com'))
I am going to send an email to a bunch of people listed in a .csv
containing a html image using python. I have got this to work fine using the code snippet below, however when it has sent, it appears in the recipient’s inbox with the full email ("****@gmail.com") and I would like for it to just say my name, for example "dezza". I have already changed the name on gmail (and when I send anything from the gmail client it does appear as just "dezza") but it doesnt roll over to python. Is there any way to do this?
Please let me know if there is anything unclear in my question. Thanks!
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Test 1"
html = f"""
<html>
<body>
<img src="cid:Mailtrapimage">
</body>
</html>
"""
part = MIMEText(html, "html")
msg.attach(part)
with open(imgfile, 'rb') as fp:
img = MIMEImage(fp.read())
fp.close
img.add_header('Content-ID', '<Mailtrapimage>')
msg.attach(img)
# Send the email (this example assumes SMTP authentication is required)
s = smtplib.SMTP('smtp.gmail.com', 587) # creates SMTP session
s.starttls() # start TLS for security
s.login(fromaddr, password)
s.send_message(msg)
s.quit()
Just like that
fromaddr = "dezza <****@gmail.com>"
You can do it with formataddr
function:
import email.utils
msg["From"] = email.utils.formataddr((sender_name, sender_email))
in your example it will be:
msg["From"] = email.utils.formataddr(('dezza', '****@gmail.com'))