Today's Agenda
Prerequisite
- Have an email account to send the emails.
- Have Python 3 installed over their systems that can be used to run the code. Check for python version using: python --version
- And finally, who are eager to learn and try such useful example.
Let's get started
# Import all the required libraries
import smtplib
import json
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import string
import base64
from email.encoders import encode_base64
# function to send the email
def sendEmail():
# initialise variables
username = "SENDER'S_EMAIL_ID"
password = "SENDER'S_EMAIL_PASSWORD"
host = "smtp.gmail.com"
port = "587"
sender_email ="SENDER'S_EMAIL_ID"
new = "RECEIVER'S_EMAIL_ID1, RECEIVER'S_EMAIL_ID2, RECEIVER'S_EMAIL_ID3"
receiver_email = new.split(",")
message = MIMEMultipart("alternative")
message["Subject"] = "Application for a Coffee date!"
message["From"] = "SENDER'S_EMAIL_ID"
furl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
file = requests.get(furl, allow_redirects=True)
attachfile = open('/tmp/attachment', 'wb')
attachfile.write(file.content)
attachfile.close()
name_list = furl.split("/")
name = name_list[-1]
attach_file=MIMEApplication(open("/tmp/attachment","rb").read())
attach_file.add_header('Content-Disposition', 'attachment', filename=name)
message.attach(attach_file)
html = "Reply with the place and time."
part2 = MIMEText(html, "html")
message.attach(part2)
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
print('Sent')
return {
'statusCode': 200,
'body': json.dumps('sent')
}
# function call
if __name__ == "__main__" sendEmail()
Comments
Post a Comment