How to do it...

  1. Import the smtplib and email modules:
>>> import smtplib
>>> from email.mime.multipart import MIMEMultipart
>>> from email.mime.text import MIMEText
  1. Set up the credentials, replacing these with your own ones. For testing purposes, we'll send to the same email, but feel free to use a different address:
>>> USER = '[email protected]'
>>> PASSWORD = 'YourPassword'
>>> sent_from = USER
>>> send_to = [USER]
  1. Define the data to be sent. Notice the two alternatives, a plain-text one and an HTML one:
>>> text = "Hi!
This is the text version linking to https://www.packtpub.com/
Cheers!"
>>> html = """<html><head></head><body>
... <p>Hi!<br>
... This is the HTML version linking to <a href="https://www.packtpub.com/">Packt</a><br>
... </p>
... </body></html>
"""
  1. Compose the message as a MIME multipart, including subject, to, and from:
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'An interesting email'
>>> msg['From'] = sent_from
>>> msg['To'] = ', '.join(send_to)
  1. Fill the data content parts of the email:
>>> part_plain = MIMEText(text, 'plain')
>>> part_html = MIMEText(html, 'html')
>>> msg.attach(part_plain)
>>> msg.attach(part_html)

  1. Send the email, using the SMTP SSL protocol:
>>> with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
... server.login(USER, PASSWORD)
... server.sendmail(sent_from, send_to, msg.as_string())
  1. The email is sent. Check your email account for the message. Checking the original email, you can see the full raw email, with elements in both HTML and plain-text. The email is presented redacted:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.165.167