Skip to content

Instantly share code, notes, and snippets.

@v42me
Last active October 11, 2023 20:34
Show Gist options
  • Save v42me/34db97764daf69fd1ff5 to your computer and use it in GitHub Desktop.
Save v42me/34db97764daf69fd1ff5 to your computer and use it in GitHub Desktop.
smtp displayname python
#send html email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
msg = MIMEMultipart('alternative')
msg['From'] = formataddr((str(Header('MyWebsite', 'utf-8')), '[email protected]'))
msg['To'] = '[email protected]'
html = "email contents"
# Record the MIME types of text/html.
msg.attach(MIMEText(html, 'html'))
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail('[email protected]', '[email protected]', msg.as_string())
s.quit()
@wprudencio
Copy link

Tks

@mralecthomas
Copy link

Thanks, was having issues displaying the from address correctly!

@dvershinin
Copy link

The str(Header(...)) casting seems completely redundant.
This works fine:

msg['From'] = formataddr(('MyWebsite', '[email protected]'))

The formataddr defaults to using Unicode.

As far as s.sendmail('[email protected]', '[email protected]', msg.as_string()), you are hardcoding things twice.
Use the s.send_message(msg) instead.

@NahueTB
Copy link

NahueTB commented Jul 5, 2021

The str(Header(...)) casting seems completely redundant.
This works fine:

msg['From'] = formataddr(('MyWebsite', '[email protected]'))

The formataddr defaults to using Unicode.

As far as s.sendmail('[email protected]', '[email protected]', msg.as_string()), you are hardcoding things twice.
Use the s.send_message(msg) instead.

This works perfectly.
Thanks to both.

@oscarmolinar
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment