jawjaw
jawjaw

Reputation: 157

PYTHON/OUTLOOK Sending e-mails through PYTHON with DOCX

I have to send mails through python. It works. It is almost done. The only problem is that I have to keep the formatting too. So either I have to send e mail as HTML (and then rewrite template with html instead of .docx) OR copy .docx file with extension Anybody has any ideas how to do this? Thanks guys.

import win32com.client as win32
import fileinput as fi 
from docx import Document

outlook = win32.Dispatch('outlook.application')

path_in = 'maillist.csv'
input_file = open(path_in, 'r')
document = Document('template.docx')
document_html = open('template.html', 'r')

print(temp)
def filecount(fname):
        for line in fi.input(fname):
            pass
        return fi.lineno()

print("Total mails %s" % (filecount(path_in)))
count = 0
for line in input_file:
    if (count>16):
        name = line.split(";")[0]
        mail_adress = line.split(";")[1]
        subject = line.split(";")[2]
        print ("%s:%s:%s:" % (name, mail_adress, subject))
        mail = outlook.CreateItem(0)
        mail.To = mail_adress
        mail.Subject = subject
        mail.body = temp.replace("XXXNAMEXXX", name)
        mail.send
    else:
        count+=1

Upvotes: 0

Views: 384

Answers (1)

RasikhJ
RasikhJ

Reputation: 611

Try adding the .RTFBody and/or .HTMLBody methods to the document objects :

    document = Document('template.docx').RTFBody
    document_html = open('template.html', 'r').HTMLBody

Also, I'm not sure if it makes much of a difference but, for convention's sake, I like to capitalize the first letter of the method for the mailItem object.

Let me know if that works.

Upvotes: 0

Related Questions