下面是一些代碼,我已經用於此目的的幾年:
from __future__ import division, print_function
import os, uuid
import itertools as it
from win32com.client import DispatchEx
import pywintypes # for exception
def send_mail(subject,body_text,sendto,copyto=None,blindcopyto=None,
attach=None):
session = DispatchEx('Lotus.NotesSession')
session.Initialize('your_password')
server_name = 'your/server'
db_name = 'your/database.nsf'
db = session.getDatabase(server_name, db_name)
if not db.IsOpen:
try:
db.Open()
except pywintypes.com_error:
print('could not open database: {}'.format(db_name))
doc = db.CreateDocument()
doc.ReplaceItemValue("Form","Memo")
doc.ReplaceItemValue("Subject",subject)
# assign random uid because sometimes Lotus Notes tries to reuse the same one
uid = str(uuid.uuid4().hex)
doc.ReplaceItemValue('UNIVERSALID',uid)
# "SendTo" MUST be populated otherwise you get this error:
# 'No recipient list for Send operation'
doc.ReplaceItemValue("SendTo", sendto)
if copyto is not None:
doc.ReplaceItemValue("CopyTo", copyto)
if blindcopyto is not None:
doc.ReplaceItemValue("BlindCopyTo", blindcopyto)
# body
body = doc.CreateRichTextItem("Body")
body.AppendText(body_text)
# attachment
if attach is not None:
attachment = doc.CreateRichTextItem("Attachment")
for att in attach:
attachment.EmbedObject(1454, "", att, "Attachment")
# save in `Sent` view; default is False
doc.SaveMessageOnSend = True
doc.Send(False)
if __name__ == '__main__':
subject = "test subject"
body = "test body"
sendto = ['[email protected]',]
files = ['/path/to/a/file.txt','/path/to/another/file.txt']
attachment = it.takewhile(lambda x: os.path.exists(x), files)
send_mail(subject, body, sendto, attach=attachment)
伯尼嗨,這 代碼工作完美。解決了我的問題,非常感謝您的幫助! – Fernando 2014-09-26 19:30:46
好的。別客氣。歡呼聲,並愉快地編碼給你 – bernie 2014-09-26 20:31:18
嗨伯尼,我在我的電腦做了本地測試,它的工作原理,但是當我在另一臺電腦上測試時,這同樣不起作用。我收到以下消息:「發生異常....無法打開數據庫names.nsf」。我不明白,因爲Lotus Notes的配置與其他機器相同。我檢查了數據庫是否在Lotus Notes的工作區中,以及我正在使用的服務器「」。你有一些關於這個問題的想法嗎? – Fernando 2014-09-30 17:45:35