Last active
October 16, 2021 15:30
-
-
Save vladwa/ad3e82d24f7da6cba68e472e9b15582b to your computer and use it in GitHub Desktop.
Python code to send an email with attachment and TLS protocol enabled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
@author: vladwa | |
@Email : [email protected] | |
''' | |
# importing the smtplib library | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.base import MIMEBase | |
from email.mime.text import MIMEText | |
from email.utils import formatdate | |
from email import encoders | |
def send_mail(subject,send_from,send_to,file1,smtpServer,smtpPort,isTls=True): | |
"""Sends a email with attachment. | |
:param subject: Email subject. | |
:param send_from: From email address. | |
:param send_to: To email address. | |
:param file: Filename(Absolute path) to attached as part of email. | |
:param smtpServer: SMTP server address. | |
:param smtpPort: SMTP server port. | |
""" | |
fileName=file1 | |
sendfrom=send_from | |
send_to=send_to | |
server=smtpServer | |
port=smtpPort | |
text = """ Hello All , | |
Attached document for the same | |
-BR, | |
"""+send_from | |
msg = MIMEMultipart() | |
msg['From'] = sendfrom | |
msg['To'] = send_to | |
msg['Date'] = formatdate(localtime = True) | |
msg['Subject'] = subject | |
msg.attach(MIMEText(text)) | |
part = MIMEBase('application', "octet-stream") | |
part.set_payload(open(fileName, "rb").read()) | |
encoders.encode_base64(part) | |
part.add_header('Content-Disposition', 'attachment; filename='+fileName) | |
msg.attach(part) | |
smtp = smtplib.SMTP(server, port) | |
if isTls: | |
smtp.ehlo() | |
smtp.starttls() | |
#smtp.login(username,password) | |
smtp.sendmail(msg['From'], [msg['To']], msg.as_string()) | |
smtp.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment