2013年1月30日 星期三

[Python] Sending Plain-text email with outlook



# -*- coding: utf-8 -*-
#
# note: can't send HTML email
#
import win32com.client
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "I AM SUBJECT!!"
newMail.Body = "I AM IN THE BODY\nSO AM I!!!"
newMail.To = "victor_hsu@compalcomm.com"
newMail.CC = "victor_hsu@compalcomm.com"
#newMail.BCC = "address"
#attachment1 = "Path to attachment no. 1"
#attachment2 = "Path to attachment no. 2"
#newMail.Attachments.Add(attachment1)
#newMail.Attachments.Add(attachment2)
#newMail.display()
newMail.Send()

[Python]Automatic Email with Word & Python


Below is a python script to send Email with Word Merge Mail feature under Windows environment.

Environment: Win7 professional
Office: 2010 English version
Python 2.7

note:
1. Remember to run Makepy and choose Microsoft Word 14.0 Object Library(8.5) first.
==========================================

# -*- coding: utf-8 -*-
#
# Word Merge to Email
#
import win32com
from win32com.client import Dispatch, constants
import time,os

const=win32com.client.constants

doc_template_name = os.path.abspath('WordEmail2_template2.docx')
data_source_name = os.path.abspath('recipient.csv')

app = win32com.client.Dispatch("Word.Application")
app.Visible = 1
app.DisplayAlerts = 0

doc_template = app.Documents.Open(doc_template_name)
mm = doc_template.MailMerge

#attach data source to template
mm.OpenDataSource(data_source_name)

#
#send the merge result to Email
mm.MainDocumentType = const.wdEMail
mm.Destination = const.wdSendToEmail
mm.MailAddressFieldName = "EMail"
mm.MailFormat = const.wdMailFormatHTML
mm.MailSubject = "This is a test mail from Python Win32---"+time.strftime('%Y_%m_%d_%H_%M_%S')
mm.MailFormat = const.wdMailFormatHTML

#merge just two record - this step may be redundant
mm.DataSource.FirstRecord = 1
mm.DataSource.LastRecord = 2
mm.SuppressBlankLines = True

#merge
mm.Execute()
#mm.Execute(Pause=False)

#cleanup
doc_template.Close()
app.Quit()