'How to Add a text in Email Body with a attachment
Here I have made this code to send mails with an attachment. I need to write "Dear All, Please find attached mail" on email body and add attachement.
# Define the HTML document
mail_content = '''Dear All,
Please find below attachement
'''
# Define a function to attach files as MIMEApplication to the email
##############################################################
def attach_file_to_email(email_message, filename):
# Open the attachment file for reading in binary mode, and make it a MIMEApplication class
with open(filename, "rb") as f:
file_attachment = MIMEApplication(f.read())
# Add header/name to the attachments
file_attachment.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
# Attach the file to the message
email_message.attach(file_attachment)
##############################################################
# Set up the email addresses and password. Please replace below with your email address and password
email_from = '[email protected]'
email_to = '[email protected]'
# Generate today's date to be included in the email Subject
date_str = pd.Timestamp.today().strftime('%Y-%m-%d')
# Create a MIMEMultipart class, and set up the From, To, Subject fields
email_message = MIMEMultipart()
email_message['From'] = email_from
email_message['To'] = email_to
email_message['Cc'] = Cc
email_message['Subject'] = f'Report email - {date_str}'
# Attach the html doc defined earlier, as a MIMEText html content type to the MIME message
email_message.attach(MIMEText(html, "html"))
# Attach more (documents)
##############################################################
attach_file_to_email(email_message, '/data/Stat20220419.csv')
##############################################################
# Convert it as a string
email_string = email_message.as_string()
try:
smtpObj = smtplib.SMTP('mail.protection.outlook.com',25)
smtpObj.sendmail(email_from, ['[email protected]], email_string)
print ("Successfully sent email")
except smtplib.SMTPException:
pass
except smtplib.socket.error:
pass
Can someone show me how to add to the mail_content to mail body. I have used email_message.attach but it is attaching anothe text file with the text. But I need to show just text in the body.Can someone help?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
