I am using python and below is the image from word file that i need to get to send email via SMTP.
So far i am able to get ONLY text and send it with a success but not the image.
I have tried many things including MIMEImage
and what not. I can't even paste my code here now as it will make no sense. Please help me out. Last when I tried to combine the body string with the image as_string
it gave me the error for being too long due to encoding.
P.S. I want to be able to run it a loop and sending 3 4 emails. I am successful in sending the text ONLY.
Here is an Example
You can use docx2txt
module to Extract the Text & Images drom a word document
import os , docx2txt
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Extract the text from the file
# Extract the images from the file
images = []
# The text variable contains the text from the Word document & the 'img' contains
# the Extracted images from the Document
text = docx2txt.process("example.docx", './img/') # create the folder before hand
directory = './img/'
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
images.append(f)
# Create the email message
sender= 'sender@gmail.com'
receiver = 'receiver@gmail.com'
msg = MIMEMultipart()
msg['Subject'] = 'Example Email'
msg['From'] = sender
msg['To'] = receiver
# Attach the text data and Hyperlink
msg.attach(MIMEText(text))
msg.attach(MIMEText(u'<a href="www.Your Link to the WebSite.com">Tiktok4Realtors.com</a>','html'))
# Attach the images
for img in images:
with open(img, 'rb') as f:
img_data = f.read()
image = MIMEApplication(img_data, _subtype='png')
image.add_header('content-disposition', 'attachment', filename=img)
msg.attach(image)
# Send the email
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()# to enable security
server.login(sender, 'senders pasword')
server.sendmail(sender,receiver, msg.as_string())
server.quit()