Steps to send mail with attachments from your Gmail account:
- To add an attachment, you need to import:
- smtplib import
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- from email.mime.base import MIMEBase
- from encoders email import
Here are some libraries that will make our job simple. These are native libraries and you don’t need to import any external library to do this.
- First, create a MIMEMultipart instance, namely "msg" to start.
- Specify the sender’s email ID, recipient’s email ID and subject in the From, To, and Subject keys of the generated msg instance.
- On a line, write the body of the message you want to send, namely the body. Now attach the body with the msg instance using the attach function.
- Open the file you want to attach in "rb" mode. Then create a MIMEBase instance with two parameters. The first — this is _maintype and the other is — _subtype. It is the base class for all MIME-specific Message subclasses.
Please note that "_maintype" is the primary Content-Type (such as text or image), and "_subtype" is the secondary type of Content-Type (such as plain or gif or other media).
- set_payload is used to change the payload of the encoded form. Encode it in encode_base64. Finally, attach the file with the MIMEMultipart-generated msg instance.
- You can use loops to send emails to multiple people.
- This code is simple to implement. But this won’t work if you’ve enabled 2-Step Verification on your Gmail account. You must first turn off two-step verification.
- By using this method, Gmail will always put your mail in the main section and sent emails will not be spam.
This article is provided by Rishabh Bansal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.