简体   繁体   中英

Sending Email to outlook using gmail server in python

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 = 'xyz@gmail.com'
EMAIL_PASSWORD = 'xyz'
smtp_server = "smtp.gmail.com"
message = EmailMessage()
message['Subject'] = 'This is my first Python email'
message['From'] = EMAIL_ADDRESS
message['To'] = ["abc@gmail.com", "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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM