Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Automate backup with Python Script
Next article icon

In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python. 

We'll be using two libraries for this: email, andsmtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to build our email message.

  • MIMEText: It consists of simple text. This will be the body of the email.
  • MIMEImage: This would allow us to add images to our emails.
  • MIMEAudio: If we wish to add audio files, we may do it easily with the help of this subclass.
  • MIMEApplication: This can be used to add anything or any other attachments.

Step-by-step Implementation

Step 1:Import the following modules

Python3
fromemail.mime.textimportMIMETextfromemail.mime.imageimportMIMEImagefromemail.mime.applicationimportMIMEApplicationfromemail.mime.multipartimportMIMEMultipartimportsmtplibimportos

Step 2:Let's set up a connection to our email server.

  • Provide the server address and port number to initiate ourSMTPconnection
  • Then we'll usesmtp.ehloto send anEHLO(Extended Hello) command.
  • Now, we'll usesmtp.starttlsto enable transport layer security (TLS) encryption.
Python3
smtp=smtplib.SMTP('smtp.gmail.com',587)smtp.ehlo()smtp.starttls()smtp.login('YourMail@gmail.com','Your Password')

Step 3:Now, built the message content.

  • Assign theMIMEMultipartobject to the msg variable after initializing it.
  • TheMIMETextfunction will be used to attach text.
Python3
msg=MIMEMultipart()msg['Subject']=subjectmsg.attach(MIMEText(text))

Step 4:Let's look at how to attach pictures and multiple attachments.

Attaching Images: 

  • First, read the image as binary data.
  • Attach the image data toMIMEMultipartusingMIMEImage, we add the given filename useos.basename
Python3
img_data=open(one_img,'rb').read()msg.attach(MIMEImage(img_data,name=os.path.basename(one_img)))

Attaching Several Files:

  • Read in the attachment usingMIMEApplication.
  • Then we edit the attached file metadata.
  • Finally, add the attachment to our message object.
Python3
withopen(one_attachment,'rb')asf:file=MIMEApplication(f.read(),name=os.path.basename(one_attachment))file['Content-Disposition']=f'attachment;\    filename="{os.path.basename(one_attachment)}"'msg.attach(file)

Step 5:The last step is to send the email.

  • Make a list of all the emails you want to send.
  • Then, by using thesendmail function, pass parameters such as from where, to where, and the message content.
  • At last, just quit the server connection.
Python3
to=["klm@gmail.com","xyz@gmail.com","abc@gmail.com"]smtp.sendmail(from_addr="Your Login Email",to_addrs=to,msg=msg.as_string())smtp.quit()

Below is the full implementation:

Python3
# Import the following modulefromemail.mime.textimportMIMETextfromemail.mime.imageimportMIMEImagefromemail.mime.applicationimportMIMEApplicationfromemail.mime.multipartimportMIMEMultipartimportsmtplibimportos# initialize connection to our# email server, we will use gmail heresmtp=smtplib.SMTP('smtp.gmail.com',587)smtp.ehlo()smtp.starttls()# Login with your email and passwordsmtp.login('Your Email','Your Password')# send our email message 'msg' to our bossdefmessage(subject="Python Notification",text="",img=None,attachment=None):# build message contentsmsg=MIMEMultipart()# Add Subjectmsg['Subject']=subject# Add text contentsmsg.attach(MIMEText(text))# Check if we have anything# given in the img parameterifimgisnotNone:# Check whether we have the lists of images or not!iftype(img)isnotlist:# if it isn't a list, make it oneimg=[img]# Now iterate through our listforone_imginimg:# read the image binary dataimg_data=open(one_img,'rb').read()# Attach the image data to MIMEMultipart# using MIMEImage, we add the given filename use os.basenamemsg.attach(MIMEImage(img_data,name=os.path.basename(one_img)))# We do the same for# attachments as we did for imagesifattachmentisnotNone:# Check whether we have the# lists of attachments or not!iftype(attachment)isnotlist:# if it isn't a list, make it oneattachment=[attachment]forone_attachmentinattachment:withopen(one_attachment,'rb')asf:# Read in the attachment# using MIMEApplicationfile=MIMEApplication(f.read(),name=os.path.basename(one_attachment))file['Content-Disposition']=f'attachment;\            filename="{os.path.basename(one_attachment)}"'# At last, Add the attachment to our message objectmsg.attach(file)returnmsg# Call the message functionmsg=message("Good!","Hi there!",r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",r"C:\Users\Dell\Desktop\slack.py")# Make a list of emails, where you wanna send mailto=["ABC@gmail.com","XYZ@gmail.com","insaaf@gmail.com"]# Provide some data to the sendmail function!smtp.sendmail(from_addr="hello@gmail.com",to_addrs=to,msg=msg.as_string())# Finally, don't forget to close the connectionsmtp.quit()

Output: 

Schedule Email Messages

For scheduling the mail, we will make use of theschedulepackage in python. It is very lightweight and easy to use. 

Install the module 

pip install schedule

Now look at the different functions that are defined in aschedule module and their use:

The below function will call the function mail every 2 seconds.

schedule.every(2).seconds.do(mail)

This will call the function mail every 10 minutes.

schedule.every(10).minutes.do(mail)

This will call the function in every hour.

schedule.every().hour.do(mail)

Calling every day at 10:30 AM.

schedule.every().day.at("10:30").do(mail)

Calling a particular day.

schedule.every().monday.do(mail)

Below is the implementation:

Python3
importscheduleimporttimefromemail.mime.textimportMIMETextfromemail.mime.imageimportMIMEImagefromemail.mime.applicationimportMIMEApplicationfromemail.mime.multipartimportMIMEMultipartimportsmtplibimportos# send our email message 'msg' to our bossdefmessage(subject="Python Notification",text="",img=None,attachment=None):# build message contentsmsg=MIMEMultipart()# Add Subjectmsg['Subject']=subject# Add text contentsmsg.attach(MIMEText(text))# Check if we have anything# given in the img parameterifimgisnotNone:# Check whether we have the# lists of images or not!iftype(img)isnotlist:# if it isn't a list, make it oneimg=[img]# Now iterate through our listforone_imginimg:# read the image binary dataimg_data=open(one_img,'rb').read()# Attach the image data to MIMEMultipart# using MIMEImage,# we add the given filename use os.basenamemsg.attach(MIMEImage(img_data,name=os.path.basename(one_img)))# We do the same for attachments# as we did for imagesifattachmentisnotNone:# Check whether we have the# lists of attachments or not!iftype(attachment)isnotlist:# if it isn't a list, make it oneattachment=[attachment]forone_attachmentinattachment:withopen(one_attachment,'rb')asf:# Read in the attachment using MIMEApplicationfile=MIMEApplication(f.read(),name=os.path.basename(one_attachment))file['Content-Disposition']=f'attachment;\            filename="{os.path.basename(one_attachment)}"'# At last, Add the attachment to our message objectmsg.attach(file)returnmsgdefmail():# initialize connection to our email server,# we will use gmail heresmtp=smtplib.SMTP('smtp.gmail.com',587)smtp.ehlo()smtp.starttls()# Login with your email and passwordsmtp.login('Email','Password')# Call the message functionmsg=message("Good!","Hi there!",r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",r"C:\Users\Dell\Desktop\slack.py")# Make a list of emails, where you wanna send mailto=["ABC@gmail.com","XYZ@gmail.com","insaaf@gmail.com"]# Provide some data to the sendmail function!smtp.sendmail(from_addr="hello@gmail.com",to_addrs=to,msg=msg.as_string())# Finally, don't forget to close the connectionsmtp.quit()schedule.every(2).seconds.do(mail)schedule.every(10).minutes.do(mail)schedule.every().hour.do(mail)schedule.every().day.at("10:30").do(mail)schedule.every(5).to(10).minutes.do(mail)schedule.every().monday.do(mail)schedule.every().wednesday.at("13:15").do(mail)schedule.every().minute.at(":17").do(mail)whileTrue:schedule.run_pending()time.sleep(1)

Output:


How to Send an Automated Email Messages in Python
Video Thumbnail

How to Send an Automated Email Messages in Python

Video Thumbnail

How to Send Automated Email Messages in Python

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp