- Now we have to send .txt files or excel files in the mail using python language.
- smtplib module is used to make communication with a mail server to send mail.
- from email.mime.multipart package is used to make MIME conventions for the multipart data or it can be created by a client as part of creating a new MimeMessage.We used MIME for enhanced message security.
- MIMEMultipart() method is used to encodes ['From'], ['To'], and ['Subject'] in the Python documentation.
- Now we can attach the body of the email to the MIME message.
- Provide the name of the file that we want to send via mail.
- In open() method we have to provide the path of a file with permission of rb . Here 'r' means just for read the file, We can also open a file in “rb” (read binary), “w” (write), “a” (append), or “wb” (write binary). Note that if you use either “w” or “wb”, Python will overwrite the file.
- MIMEBase('application', 'octet-stream') used for application or a document that must be opened in an application, such as a spreadsheet or word processor. application/octet-stream attachment help to open all kind of content in an email.
- set_payload will load the file from a given path with reading permission
- Encode data by calling the encode_base64() function. We encode our 'p' variable in which we load a spreadsheet.
- Content-Disposition is a header indicating. It used to display our attachment in which we store the path of a file. The file will be stored in string format.
- Now a message attached with the file.
- Create SMTP connection with the help of server request and port no.
- s.starttls() method is used to start TLS (Transfer layer security).
- Now provide sender mail id with password.
- msg.as_string() method is used to convert multipart message into string.
- sendmail() method is used to send mail.
To send file using python language, we have to give some permission in google account. open sender google account -> select security option ->click on Less secure app access ->Allow less secure apps: ON This permission allows us to send mail.
Since this is a python file, hence it can be run using following command
python mail.py
python3 mail.py