3 ways to send emails with only few lines of code and Gmail – Python – Part 3

We will see how to send a simple email with the help of three different programming languages: Javascript, Ruby and Python
Before you start you need to create a Gmail account.
Do not forget to accept and allow the “Less secure apps” access in order use your scripts with your Gmail smtp connection.
I’ll let you do this on your own, you don’t need a tutorial for this

Python

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

Enter fullscreen mode Exit fullscreen mode

  • Define Gmail account info and recipient email:
# The email addresses and password sender_address = 'youremail@gmail.com'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = 'myfriend@yopmail.com'
mail_content = 'Easy peazy lemon squeezy'

Enter fullscreen mode Exit fullscreen mode

  • Setup the MIME:
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Sending email using Python'
message.attach(MIMEText(mail_content, 'plain'))

Enter fullscreen mode Exit fullscreen mode

  • Create SMTP session for sending the mail:
session = smtplib.SMTP('smtp.gmail.com', gmail_port)
session.starttls() # enable security session.login(sender_address, sender_password)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

print('Email Sent')

Enter fullscreen mode Exit fullscreen mode

Here the final code:

import smtplib

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

# The email addresses and password sender_address = 'youremail@gmail.com'
sender_password = 'yourpassword'
gmail_port = 587

receiver_address = 'myfriend@yopmail.com'
mail_content = 'Easy peezy lemon squeezy'

# Setup the MIME message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Sending email using Python'

# The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain'))

# Create SMTP session for sending the mail session = smtplib.SMTP('smtp.gmail.com', gmail_port)
session.starttls() # enable security session.login(sender_address, sender_password)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

print('Email Sent')

Enter fullscreen mode Exit fullscreen mode

The power of Python

What’s next?

With those scripts, we went through the basics of the module, gem and library (read the docs ) but you can also do amazing things with them like loops, sending attachments, automated things… feel free to do want you want.

Thanks for reading this tiny scripts serie
See you soon @Kinoba

Table of contents

原文链接:3 ways to send emails with only few lines of code and Gmail – Python – Part 3

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容