2014-09-26 186 views
2

我需要使用python在Lotus Notes中发送邮件的帮助,看起来win32com可以这样做,但我没有找到任何完整的示例或教程。我的想法是一个简单的功能吧:使用python发送邮件在Lotus Notes中

from win32com.client import Dispatch 
import smtplib 

def SendMail(subject, text, user): 
    session = Dispatch('Lotus.NotesSession') 
    session.Initialize('???') 
    db = session.getDatabase("", "") 
    db.OpenMail(); 

有些建议吗?谢谢!

回答

5

下面是一些代码,我已经用于此目的的几年:

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) 
+0

伯尼嗨,这 代码工作完美。解决了我的问题,非常感谢您的帮助! – Fernando 2014-09-26 19:30:46

+0

好的。别客气。欢呼声,并愉快地编码给你 – bernie 2014-09-26 20:31:18

+0

嗨伯尼,我在我的电脑做了本地测试,它的工作原理,但是当我在另一台电脑上测试时,这同样不起作用。我收到以下消息:“发生异常....无法打开数据库names.nsf”。我不明白,因为Lotus Notes的配置与其他机器相同。我检查了数据库是否在Lotus Notes的工作区中,以及我正在使用的服务器“”。你有一些关于这个问题的想法吗? – Fernando 2014-09-30 17:45:35

相关问题