Reputation: 139
I am able to send email and attachments from gmail account to gmail and outlook account. But in outlook account I am receiving corrupt file without file type and without data whereas I am receiving email in gmail account without any issue (preview is also working in gmail receiving account). How can I solve the problem?
import smtplib
from email.message import EmailMessage
import imghdr
import ssl
body = """
this is first mail by using python
Thank you! python
"""
EMAIL_ADDRESS = '[email protected]'
EMAIL_PASSWORD = 'xyz'
smtp_server = "smtp.gmail.com"
message = EmailMessage()
message['Subject'] = 'This is my first Python email'
message['From'] = EMAIL_ADDRESS
message['To'] = ["[email protected]", "user_name@company_name.com"]
message.set_content(body, 'plain')
with open("path_to_image.png", 'rb') as img:
img_data = img.read()
img_type = imghdr.what(img.name)
message.add_attachment(img_data, maintype='image', subtype=img_type, filename='filename')
default_context = ssl.create_default_context()
print("sending...")
with smtplib.SMTP_SSL(smtp_server, port=465, context=default_context) as server:
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.send_message(message)
print("success!!!")
user_name@company_name.com is my private company outlook email address
Upvotes: 0
Views: 930
Reputation: 7287
You need to use the proper MIME type to specify the type of content. Replace plain
with text/plain
for the body and image
with image/png
for the image. That way outlook (or any mail client for that matter) will know how to present the body and how to preview the attachment.
Upvotes: 1