def _send_message(self, new_message_wrapper): try: # SMTP authenticate if self._schema.imap_account.is_gmail: oauth = GoogleOauth2() response = oauth.RefreshToken( self._schema.imap_account.refresh_token) auth_string = oauth.generate_oauth2_string( self._schema.imap_account.email, response['access_token'], as_base64=True) s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo(CLIENT_ID) s.starttls() s.docmd('AUTH', 'XOAUTH2 ' + auth_string) else: s = smtplib.SMTP( self._schema.imap_account.host.replace("imap", "smtp"), 587) s.login( self._schema.imap_account.email, decrypt_plain_password(self._schema.imap_account.password)) s.ehlo() # TODO check if it sent to cc-ers s.sendmail(self._schema.imap_account.email, new_message_wrapper["To"], new_message_wrapper.as_string()) except Exception as e: print(e)
def _send_message(self, new_message_wrapper): # type: (MIMEMultipart) -> None """Send out a message with the user's credential """ try: # SMTP authenticate if self._imap_account.is_oauth: oauth = GoogleOauth2() response = oauth.RefreshToken(self._imap_account.refresh_token) auth_string = oauth.generate_oauth2_string( self._imap_account.email, response['access_token'], as_base64=True) s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo(CLIENT_ID) s.starttls() s.docmd('AUTH', 'XOAUTH2 ' + auth_string) else: try: smtp_host = "" login_id = self._imap_account.email if "imap.exchange.mit.edu" == self._imap_account.host: smtp_host = "outgoing.mit.edu" login_id = login_id.split("@")[0] else: smtp_host = self._imap_account.host.replace( "imap", "smtp") s = smtplib.SMTP(smtp_host, 587) except Exception: raise NameError s.ehlo() s.starttls() s.ehlo() s.login(login_id, decrypt_plain_password(self._imap_account.password)) receip_list = [] for i in ["To", "Cc", "Bcc"]: if i in new_message_wrapper and new_message_wrapper[i]: receip_list.append(new_message_wrapper[i]) # TODO check if it sent to cc-ers s.sendmail(self._imap_account.email, ', '.join(receip_list), new_message_wrapper.as_string()) except NameError: raise RuntimeError( "Error occur during sending your message: it has been reported to admins" ) except Exception as e: logger.exception("%s %s" % (e, traceback.format_exc())) raise RuntimeError('Failed to send a message: %s' % str(e))
def authenticate(imap_account): # type: (ImapAccount) -> t.Dict[t.AnyStr, t.Any] """Authenticate an imap_account from the database Returns a dictionary with the following keys status is whether authentication succeeded imap is the authorized ImapClient if status is true Args: imap_account (ImapAccount): ImapAccount stored in the database Returns: t.Dict: dictionary of information about the authentication """ res = {'status' : False, 'imap_error': False, 'imap_log': "", 'imap': None} # create an imap client imap_client = IMAPClient(imap_account.host, use_uid=True) try: if imap_account.is_oauth: # TODO if access_token is expired, then get a new token imap_client.oauth2_login(imap_account.email, imap_account.access_token) else: password = decrypt_plain_password(imap_account.password) if "csail" in imap_account.email: imap_client.login(imap_account.email.split("@")[0], password) else: imap_client.login(imap_account.email, password) res['imap'] = imap_client res['status'] = True except IMAPClient.Error, e: try: logger.debug('try to renew token') if imap_account.is_oauth: oauth = GoogleOauth2() response = oauth.RefreshToken(imap_account.refresh_token) imap_client.oauth2_login(imap_account.email, response['access_token']) imap_account.access_token = response['access_token'] imap_account.save() res['imap'] = imap_client res['status'] = True else: # TODO this is not DRY and not useful error messages logger.error("cannot renew token for non-oauth account") res['code'] = "Can't authenticate your email" except IMAPClient.Error, e: logger.exception("IMAPClient.Error - failed to authenticate email") res['imap_error'] = e res['code'] = "Can't authenticate your email"