Update ooo320-m1
[ooovba.git] / scripting / source / pyprov / mailmerge.py
blob75d2db53370806697eb45f2486dc38a2cef7dfb2
1 # Caolan McNamara caolanm@redhat.com
2 # a simple email mailmerge component
4 # manual installation for hackers, not necessary for users
5 # cp mailmerge.py /usr/lib/openoffice.org2.0/program
6 # cd /usr/lib/openoffice.org2.0/program
7 # ./unopkg add --shared mailmerge.py
8 # edit ~/.openoffice.org2/user/registry/data/org/openoffice/Office/Writer.xcu
9 # and change EMailSupported to as follows...
10 # <prop oor:name="EMailSupported" oor:type="xs:boolean">
11 # <value>true</value>
12 # </prop>
14 import unohelper
15 import uno
16 import re
18 #to implement com::sun::star::mail::XMailServiceProvider
20 from com.sun.star.mail import XMailServiceProvider
21 from com.sun.star.mail import XMailService
22 from com.sun.star.mail import XSmtpService
23 from com.sun.star.mail import XConnectionListener
24 from com.sun.star.mail import XAuthenticator
25 from com.sun.star.mail import XMailMessage
26 from com.sun.star.mail.MailServiceType import SMTP
27 from com.sun.star.mail.MailServiceType import POP3
28 from com.sun.star.mail.MailServiceType import IMAP
29 from com.sun.star.uno import XCurrentContext
30 from com.sun.star.lang import IllegalArgumentException
31 from com.sun.star.lang import EventObject
32 from com.sun.star.mail import SendMailMessageFailedException
34 from email.MIMEBase import MIMEBase
35 from email.Message import Message
36 from email import Encoders
37 from email.Header import Header
38 from email.MIMEMultipart import MIMEMultipart
39 from email.Utils import formatdate
41 import sys, smtplib, imaplib, poplib
43 dbg = False
45 class PyMailSMTPService(unohelper.Base, XSmtpService):
46 def __init__( self, ctx ):
47 self.ctx = ctx
48 self.listeners = []
49 self.supportedtypes = ('Insecure', 'Ssl')
50 self.server = None
51 self.connectioncontext = None
52 self.notify = EventObject()
53 if dbg:
54 print >> sys.stderr, "PyMailSMPTService init"
55 def addConnectionListener(self, xListener):
56 if dbg:
57 print >> sys.stderr, "PyMailSMPTService addConnectionListener"
58 self.listeners.append(xListener)
59 def removeConnectionListener(self, xListener):
60 if dbg:
61 print >> sys.stderr, "PyMailSMPTService removeConnectionListener"
62 self.listeners.remove(xListener)
63 def getSupportedConnectionTypes(self):
64 if dbg:
65 print >> sys.stderr, "PyMailSMPTService getSupportedConnectionTypes"
66 return self.supportedtypes
67 def connect(self, xConnectionContext, xAuthenticator):
68 self.connectioncontext = xConnectionContext
69 if dbg:
70 print >> sys.stderr, "PyMailSMPTService connect"
71 server = xConnectionContext.getValueByName("ServerName")
72 if dbg:
73 print >> sys.stderr, server
74 port = xConnectionContext.getValueByName("Port")
75 if dbg:
76 print >> sys.stderr, port
77 self.server = smtplib.SMTP(server, port)
78 if dbg:
79 self.server.set_debuglevel(1)
80 connectiontype = xConnectionContext.getValueByName("ConnectionType")
81 if dbg:
82 print >> sys.stderr, connectiontype
83 if connectiontype == 'Ssl':
84 self.server.ehlo()
85 self.server.starttls()
86 self.server.ehlo()
88 user = xAuthenticator.getUserName()
89 password = xAuthenticator.getPassword()
90 if user != '':
91 if dbg:
92 print >> sys.stderr, 'Logging in, username of', user
93 self.server.login(user, password)
95 for listener in self.listeners:
96 listener.connected(self.notify)
97 def disconnect(self):
98 if dbg:
99 print >> sys.stderr, "PyMailSMPTService disconnect"
100 if self.server:
101 self.server.quit()
102 self.server = None
103 for listener in self.listeners:
104 listener.disconnected(self.notify)
105 def isConnected(self):
106 if dbg:
107 print >> sys.stderr, "PyMailSMPTService isConnected"
108 return self.server != None
109 def getCurrentConnectionContext(self):
110 if dbg:
111 print >> sys.stderr, "PyMailSMPTService getCurrentConnectionContext"
112 return self.connectioncontext
113 def sendMailMessage(self, xMailMessage):
114 COMMASPACE = ', '
116 if dbg:
117 print >> sys.stderr, "PyMailSMPTService sendMailMessage"
118 recipients = xMailMessage.getRecipients()
119 sendermail = xMailMessage.SenderAddress
120 sendername = xMailMessage.SenderName
121 subject = xMailMessage.Subject
122 ccrecipients = xMailMessage.getCcRecipients()
123 bccrecipients = xMailMessage.getBccRecipients()
124 if dbg:
125 print >> sys.stderr, "PyMailSMPTService subject", subject
126 print >> sys.stderr, "PyMailSMPTService from", sendername.encode('utf-8')
127 print >> sys.stderr, "PyMailSMTPService from", sendermail
128 print >> sys.stderr, "PyMailSMPTService send to", recipients
130 attachments = xMailMessage.getAttachments()
132 content = xMailMessage.Body
133 flavors = content.getTransferDataFlavors()
134 flavor = flavors[0]
135 if dbg:
136 print >> sys.stderr, "PyMailSMPTService mimetype is", flavor.MimeType
137 textbody = content.getTransferData(flavor)
139 textmsg = Message()
140 mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
141 textmsg['Content-Type'] = mimeEncoding
142 textmsg['MIME-Version'] = '1.0'
143 textmsg.set_payload(textbody.encode('utf-8'))
145 if (len(attachments)):
146 msg = MIMEMultipart()
147 msg.epilogue = ''
148 msg.attach(textmsg)
149 else:
150 msg = textmsg
152 hdr = Header(sendername, 'utf-8')
153 hdr.append('<'+sendermail+'>','us-ascii')
154 msg['Subject'] = subject
155 msg['From'] = hdr
156 msg['To'] = COMMASPACE.join(recipients)
157 if len(ccrecipients):
158 msg['Cc'] = COMMASPACE.join(ccrecipients)
159 if xMailMessage.ReplyToAddress != '':
160 msg['Reply-To'] = xMailMessage.ReplyToAddress
161 msg['X-Mailer'] = "OpenOffice.org 2.0 via Caolan's mailmerge component"
163 msg['Date'] = formatdate(localtime=True)
165 for attachment in attachments:
166 content = attachment.Data
167 flavors = content.getTransferDataFlavors()
168 flavor = flavors[0]
169 ctype = flavor.MimeType
170 maintype, subtype = ctype.split('/', 1)
171 msgattachment = MIMEBase(maintype, subtype)
172 data = content.getTransferData(flavor)
173 msgattachment.set_payload(data)
174 Encoders.encode_base64(msgattachment)
175 msgattachment.add_header('Content-Disposition', 'attachment', \
176 filename=attachment.ReadableName)
177 msg.attach(msgattachment)
179 uniquer = {}
180 for key in recipients:
181 uniquer[key] = True
182 if len(ccrecipients):
183 for key in ccrecipients:
184 uniquer[key] = True
185 if len(bccrecipients):
186 for key in bccrecipients:
187 uniquer[key] = True
188 truerecipients = uniquer.keys()
190 if dbg:
191 print >> sys.stderr, "PyMailSMPTService recipients are", truerecipients
193 self.server.sendmail(sendermail, truerecipients, msg.as_string())
195 class PyMailIMAPService(unohelper.Base, XMailService):
196 def __init__( self, ctx ):
197 self.ctx = ctx
198 self.listeners = []
199 self.supportedtypes = ('Insecure', 'Ssl')
200 self.server = None
201 self.connectioncontext = None
202 if dbg:
203 print >> sys.stderr, "PyMailIMAPService init"
204 def addConnectionListener(self, xListener):
205 if dbg:
206 print >> sys.stderr, "PyMailIMAPService addConnectionListener"
207 self.listeners.append(xListener)
208 def removeConnectionListener(self, xListener):
209 if dbg:
210 print >> sys.stderr, "PyMailIMAPService removeConnectionListener"
211 self.listeners.remove(xListener)
212 def getSupportedConnectionTypes(self):
213 if dbg:
214 print >> sys.stderr, "PyMailIMAPService getSupportedConnectionTypes"
215 return self.supportedtypes
216 def connect(self, xConnectionContext, xAuthenticator):
217 if dbg:
218 print >> sys.stderr, "PyMailIMAPService connect"
220 self.connectioncontext = xConnectionContext
221 server = xConnectionContext.getValueByName("ServerName")
222 if dbg:
223 print >> sys.stderr, server
224 port = xConnectionContext.getValueByName("Port")
225 if dbg:
226 print >> sys.stderr, port
227 connectiontype = xConnectionContext.getValueByName("ConnectionType")
228 if dbg:
229 print >> sys.stderr, connectiontype
230 print >> sys.stderr, "BEFORE"
231 if connectiontype == 'Ssl':
232 self.server = imaplib.IMAP4_SSL(server, port)
233 else:
234 self.server = imaplib.IMAP4(server, port)
235 print >> sys.stderr, "AFTER"
237 user = xAuthenticator.getUserName()
238 password = xAuthenticator.getPassword()
239 if user != '':
240 if dbg:
241 print >> sys.stderr, 'Logging in, username of', user
242 self.server.login(user, password)
244 for listener in self.listeners:
245 listener.connected(self.notify)
246 def disconnect(self):
247 if dbg:
248 print >> sys.stderr, "PyMailIMAPService disconnect"
249 if self.server:
250 self.server.logout()
251 self.server = None
252 for listener in self.listeners:
253 listener.disconnected(self.notify)
254 def isConnected(self):
255 if dbg:
256 print >> sys.stderr, "PyMailIMAPService isConnected"
257 return self.server != None
258 def getCurrentConnectionContext(self):
259 if dbg:
260 print >> sys.stderr, "PyMailIMAPService getCurrentConnectionContext"
261 return self.connectioncontext
263 class PyMailPOP3Service(unohelper.Base, XMailService):
264 def __init__( self, ctx ):
265 self.ctx = ctx
266 self.listeners = []
267 self.supportedtypes = ('Insecure', 'Ssl')
268 self.server = None
269 self.connectioncontext = None
270 if dbg:
271 print >> sys.stderr, "PyMailPOP3Service init"
272 def addConnectionListener(self, xListener):
273 if dbg:
274 print >> sys.stderr, "PyMailPOP3Service addConnectionListener"
275 self.listeners.append(xListener)
276 def removeConnectionListener(self, xListener):
277 if dbg:
278 print >> sys.stderr, "PyMailPOP3Service removeConnectionListener"
279 self.listeners.remove(xListener)
280 def getSupportedConnectionTypes(self):
281 if dbg:
282 print >> sys.stderr, "PyMailPOP3Service getSupportedConnectionTypes"
283 return self.supportedtypes
284 def connect(self, xConnectionContext, xAuthenticator):
285 if dbg:
286 print >> sys.stderr, "PyMailPOP3Service connect"
288 self.connectioncontext = xConnectionContext
289 server = xConnectionContext.getValueByName("ServerName")
290 if dbg:
291 print >> sys.stderr, server
292 port = xConnectionContext.getValueByName("Port")
293 if dbg:
294 print >> sys.stderr, port
295 connectiontype = xConnectionContext.getValueByName("ConnectionType")
296 if dbg:
297 print >> sys.stderr, connectiontype
298 print >> sys.stderr, "BEFORE"
299 if connectiontype == 'Ssl':
300 self.server = poplib.POP3_SSL(server, port)
301 else:
302 self.server = poplib.POP3(server, port)
303 print >> sys.stderr, "AFTER"
305 user = xAuthenticator.getUserName()
306 password = xAuthenticator.getPassword()
307 if dbg:
308 print >> sys.stderr, 'Logging in, username of', user
309 self.server.user(user)
310 self.server.pass_(user, password)
312 for listener in self.listeners:
313 listener.connected(self.notify)
314 def disconnect(self):
315 if dbg:
316 print >> sys.stderr, "PyMailPOP3Service disconnect"
317 if self.server:
318 self.server.quit()
319 self.server = None
320 for listener in self.listeners:
321 listener.disconnected(self.notify)
322 def isConnected(self):
323 if dbg:
324 print >> sys.stderr, "PyMailPOP3Service isConnected"
325 return self.server != None
326 def getCurrentConnectionContext(self):
327 if dbg:
328 print >> sys.stderr, "PyMailPOP3Service getCurrentConnectionContext"
329 return self.connectioncontext
331 class PyMailServiceProvider(unohelper.Base, XMailServiceProvider):
332 def __init__( self, ctx ):
333 if dbg:
334 print >> sys.stderr, "PyMailServiceProvider init"
335 self.ctx = ctx
336 def create(self, aType):
337 if dbg:
338 print >> sys.stderr, "PyMailServiceProvider create with", aType
339 if aType == SMTP:
340 return PyMailSMTPService(self.ctx);
341 elif aType == POP3:
342 return PyMailPOP3Service(self.ctx);
343 elif aType == IMAP:
344 return PyMailIMAPService(self.ctx);
345 else:
346 print >> sys.stderr, "PyMailServiceProvider, unknown TYPE", aType
348 # pythonloader looks for a static g_ImplementationHelper variable
349 g_ImplementationHelper = unohelper.ImplementationHelper()
350 g_ImplementationHelper.addImplementation( \
351 PyMailServiceProvider, "org.openoffice.pyuno.MailServiceProvider",
352 ("com.sun.star.mail.MailServiceProvider",),)