def connect(self, context, authenticator): if isDebugMode(): msg = getMessage(self._ctx, g_message, 221) logMessage(self._ctx, INFO, msg, 'SmtpService', 'connect()') if self.isConnected(): raise AlreadyConnectedException() if not hasInterface(context, 'com.sun.star.uno.XCurrentContext'): raise IllegalArgumentException() if not hasInterface(authenticator, 'com.sun.star.mail.XAuthenticator'): raise IllegalArgumentException() server = context.getValueByName('ServerName') error = self._setServer(context, server) if error is not None: if isDebugMode(): msg = getMessage(self._ctx, g_message, 222, error.Message) logMessage(self._ctx, SEVERE, msg, 'SmtpService', 'connect()') raise error authentication = context.getValueByName('AuthenticationType').title() if authentication != 'None': error = self._doLogin(authentication, authenticator, server) if error is not None: if isDebugMode(): msg = getMessage(self._ctx, g_message, 223, error.Message) logMessage(self._ctx, SEVERE, msg, 'SmtpService', 'connect()') raise error self._context = context for listener in self._listeners: listener.connected(self._notify) if isDebugMode(): msg = getMessage(self._ctx, g_message, 224) logMessage(self._ctx, INFO, msg, 'SmtpService', 'connect()')
def __init__(self, ctx): if isDebugMode(): msg = getMessage(ctx, g_message, 111) logMessage(ctx, INFO, msg, 'MailServiceProvider', '__init__()') self._ctx = ctx if isDebugMode(): msg = getMessage(ctx, g_message, 112) logMessage(ctx, INFO, msg, 'MailServiceProvider', '__init__()')
def disconnect(self): if self.isConnected(): if isDebugMode(): msg = getMessage(self._ctx, g_message, 361) logMessage(self._ctx, INFO, msg, 'ImapService', 'disconnect()') self._server.logout() self._server = None self._context = None for listener in self._listeners: listener.disconnected(self._notify) if isDebugMode(): msg = getMessage(self._ctx, g_message, 362) logMessage(self._ctx, INFO, msg, 'ImapService', 'disconnect()')
def __init__(self, ctx): if isDebugMode(): msg = getMessage(ctx, g_message, 311) logMessage(ctx, INFO, msg, 'ImapService', '__init__()') self._ctx = ctx self._listeners = [] self._supportedconnection = ('Insecure', 'Ssl', 'Tls') self._supportedauthentication = ('None', 'Login', 'OAuth2') self._server = None self._context = None self._notify = EventObject(self) if isDebugMode(): msg = getMessage(ctx, g_message, 312) logMessage(ctx, INFO, msg, 'ImapService', '__init__()')
def create(self, mailtype): if isDebugMode(): msg = getMessage(self._ctx, g_message, 121, mailtype.value) logMessage(self._ctx, INFO, msg, 'MailServiceProvider', 'create()') if mailtype == SMTP: service = SmtpService(self._ctx) elif mailtype == POP3: service = Pop3Service(self._ctx) elif mailtype == IMAP: service = ImapService(self._ctx) else: e = self._getNoMailServiceProviderException(123, mailtype) logMessage(self._ctx, SEVERE, e.Message, 'MailServiceProvider', 'create()') raise e if isDebugMode(): msg = getMessage(self._ctx, g_message, 122, mailtype.value) logMessage(self._ctx, INFO, msg, 'MailServiceProvider', 'create()') return service
def connect(self, context, authenticator): if isDebugMode(): msg = getMessage(self._ctx, g_message, 321) logMessage(self._ctx, INFO, msg, 'ImapService', 'connect()') if self.isConnected(): raise AlreadyConnectedException() if not hasInterface(context, 'com.sun.star.uno.XCurrentContext'): raise IllegalArgumentException() if not hasInterface(authenticator, 'com.sun.star.mail.XAuthenticator'): raise IllegalArgumentException() self._context = context server = context.getValueByName('ServerName') port = context.getValueByName('Port') timeout = context.getValueByName('Timeout') connection = context.getValueByName('ConnectionType').title() authentication = context.getValueByName('AuthenticationType').title() if connection == 'Ssl': self._server = imapclient.IMAPClient(server, port=port, ssl=True, timeout=timeout) else: self._server = imapclient.IMAPClient(server, port=port, ssl=False, timeout=timeout) if connection == 'Tls': self._server.starttls() if authentication == 'Login': user = authenticator.getUserName() password = authenticator.getPassword() code = self._server.login(user, password) print("ImapService.connect() 1: %s" % code) elif authentication == 'Oauth2': user = authenticator.getUserName() token = getOAuth2Token(self._ctx, self, server, user) code = self._server.oauth2_login(user, token) print("ImapService.connect() 2: %s" % code) for listener in self._listeners: listener.connected(self._notify) if isDebugMode(): msg = getMessage(self._ctx, g_message, 324) logMessage(self._ctx, INFO, msg, 'ImapService', 'connect()')
def _setServer(self, context, host): error = None port = context.getValueByName('Port') timeout = context.getValueByName('Timeout') connection = context.getValueByName('ConnectionType').title() if isDebugMode(): msg = getMessage(self._ctx, g_message, 231, connection) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') try: if connection == 'Ssl': if isDebugMode(): msg = getMessage(self._ctx, g_message, 232, timeout) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') server = smtplib.SMTP_SSL(timeout=timeout) else: if isDebugMode(): msg = getMessage(self._ctx, g_message, 233, timeout) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') server = smtplib.SMTP(timeout=timeout) if isDebugMode(): server.set_debuglevel(1) code, reply = _getReply(*server.connect(host=host, port=port)) if isDebugMode(): msg = getMessage(self._ctx, g_message, 234, (host, port, code, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') if code != 220: msg = getMessage(self._ctx, g_message, 236, reply) error = ConnectException(msg, self) elif connection == 'Tls': code, reply = _getReply(*server.starttls()) if isDebugMode(): msg = getMessage(self._ctx, g_message, 235, (code, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') if code != 220: msg = getMessage(self._ctx, g_message, 236, reply) error = ConnectException(msg, self) except smtplib.SMTPConnectError as e: msg = getMessage(self._ctx, g_message, 236, getExceptionMessage(e)) error = ConnectException(msg, self) except smtplib.SMTPException as e: msg = getMessage(self._ctx, g_message, 236, getExceptionMessage(e)) error = UnknownHostException(msg, self) except Exception as e: msg = getMessage(self._ctx, g_message, 236, getExceptionMessage(e)) error = MailException(msg, self) else: self._server = server if isDebugMode() and error is None: msg = getMessage(self._ctx, g_message, 237, (connection, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_setServer()') return error
def _doLogin(self, authentication, authenticator, server): error = None user = authenticator.getUserName() if isDebugMode(): msg = getMessage(self._ctx, g_message, 241, authentication) logMessage(self._ctx, INFO, msg, 'SmtpService', '_doLogin()') try: if authentication == 'Login': password = authenticator.getPassword() if sys.version < '3': # fdo#59249 i#105669 Python 2 needs "ascii" user = user.encode('ascii') password = password.encode('ascii') code, reply = _getReply(*self._server.login(user, password)) if isDebugMode(): pwd = '*' * len(password) msg = getMessage(self._ctx, g_message, 242, (user, pwd, code, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_doLogin()') elif authentication == 'Oauth2': token = _getToken(self._ctx, self, server, user, True) self._server.ehlo_or_helo_if_needed() code, reply = _getReply( *self._server.docmd('AUTH', 'XOAUTH2 %s' % token)) if code != 235: msg = getMessage(self._ctx, g_message, 244, reply) error = AuthenticationFailedException(msg, self) if isDebugMode(): msg = getMessage(self._ctx, g_message, 243, (code, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_doLogin()') except Exception as e: msg = getMessage(self._ctx, g_message, 244, getExceptionMessage(e)) error = AuthenticationFailedException(msg, self) if isDebugMode() and error is None: msg = getMessage(self._ctx, g_message, 245, (authentication, reply)) logMessage(self._ctx, INFO, msg, 'SmtpService', '_doLogin()') return error
def sendMailMessage(self, message): msg = _getMessage(self._ctx, message) recipients = _getRecipients(message) error = None try: refused = self._server.sendmail(message.SenderAddress, recipients, msg.as_string()) except smtplib.SMTPSenderRefused as e: msg = getMessage(self._ctx, g_message, 252, (message.Subject, getExceptionMessage(e))) error = MailException(msg, self) except smtplib.SMTPRecipientsRefused as e: msg = getMessage(self._ctx, g_message, 253, (message.Subject, getExceptionMessage(e))) # TODO: return SendMailMessageFailedException in place of MailException # TODO: error = SendMailMessageFailedException(msg, self) error = MailException(msg, self) except smtplib.SMTPDataError as e: msg = getMessage(self._ctx, g_message, 253, (message.Subject, getExceptionMessage(e))) error = MailException(msg, self) except Exception as e: msg = getMessage(self._ctx, g_message, 253, (message.Subject, getExceptionMessage(e))) error = MailException(msg, self) else: if len(refused) > 0: for address, result in refused.items(): code, reply = _getReply(*result) msg = getMessage(self._ctx, g_message, 254, (message.Subject, address, code, reply)) logMessage(self._ctx, SEVERE, msg, 'SmtpService', 'sendMailMessage()') elif isDebugMode(): msg = getMessage(self._ctx, g_message, 255, message.Subject) logMessage(self._ctx, INFO, msg, 'SmtpService', 'sendMailMessage()') if error is not None: logMessage(self._ctx, SEVERE, error.Message, 'SmtpService', 'sendMailMessage()') raise error
def _getMessage(ctx, message): COMMASPACE = ', ' sendermail = message.SenderAddress sendername = message.SenderName subject = message.Subject if isDebugMode(): msg = getMessage(ctx, g_message, 251, subject) logMessage(ctx, INFO, msg, 'SmtpService', 'sendMailMessage()') textmsg = Message() content = message.Body flavors = content.getTransferDataFlavors() #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find( 'text/plain') != -1: textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub('charset=.*', 'charset=UTF-8', flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + '; charset=UTF-8' textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value if sys.version >= '3': if sys.version_info.minor < 3 or ( sys.version_info.minor == 3 and sys.version_info.micro <= 1): #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok #in python 3.3.2 onwards, but a little busted in 3.3.0 textbody = textbody.decode('iso8859-1') else: textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) else: textmsg.set_payload(textbody) break if message.hasAttachments(): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg header = Header(sendername, 'utf-8') header.append('<' + sendermail + '>', 'us-ascii') msg['Subject'] = subject msg['From'] = header msg['To'] = COMMASPACE.join(message.getRecipients()) msg['Message-ID'] = message.MessageId if message.ThreadId: msg['References'] = message.ThreadId if message.hasCcRecipients(): msg['Cc'] = COMMASPACE.join(message.getCcRecipients()) if message.ReplyToAddress != '': msg['Reply-To'] = message.ReplyToAddress xmailer = "LibreOffice / OpenOffice via smtpMailerOOo extention" try: configuration = getConfiguration(ctx, '/org.openoffice.Setup/Product') name = configuration.getByName('ooName') version = configuration.getByName('ooSetupVersion') xmailer = "%s %s via smtpMailerOOo extention" % (name, version) except: pass msg['X-Mailer'] = xmailer msg['Date'] = formatdate(localtime=True) for attachment in message.getAttachments(): content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) msg.attach(msgattachment) return msg