Using an external SMTP service

 Although most hosts and ISP providers offer support for SMTP, there are some benefits of using an external SMTP service:

  • They can guarantee a better delivery of emails
  • You will not have to configure your own server (if you use VPS)

You can find the details of Google SMTP in the following parameters:

  • SMTP server: smtp.gmail.com
  • SMTP user: Your complete Gmail user (email), for example, [email protected]
  • SMTP password: Your Gmail password
  • SMTP port: The default Gmail SMTP server port is 465 for SSL and 587 for TSL
  • TLS/SSL: Required

To send an email through the Gmail SMTP server, you need to configure it through the following service by activating the Allow less secure apps: ON option with your Google account at https://www.google.com/settings/security/lesssecureapps:

Now, we can proceed and send emails from Python. We will follow these steps to achieve this process:

  1. Create an SMTP object for the server connection
  2. Log in to your account
  3. Define the headers of your messages and login credentials
  4. Create a MIMEMultipart message object and attach the corresponding headers
  5. Attach the message to the MIMEMultipart object message
  6. Send the message

You can find the following code in the send_text_mail_from_gmail.py file:

#!/usr/bin/env python3

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

# create message object instance
message = MIMEMultipart()

# setup the parameters of the message
message['From'] = "user@domain"
message['To'] = "user@domain"
message['Subject'] = "Subject"

# add in the message body
message.attach(MIMEText("message", 'plain'))

In the previous code block we have created the message object instance and setup the parameters of the message.In the next code block we are going to create the connection with the smtp server, login with user credentials and send email with sendmail method.

#create server
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()

# Login Credentials for sending the mail
server.login(message['From'], "password")

# send the message via the server.
server.sendmail(message['From'], message['To'], message.as_string())
print("successfully sent email to %s:" % (message['To']))
server.quit()

In the previous example we have reviewed how to send an email using the Gmail SMTP server.You can test it changing the parameters of the message using your user and setting your password in the login() method credentials.

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

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