def send_message(self, msg: MIMEBase): service = get_gmail_service() rmsg = { 'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode('ascii') } try: service.users().messages().send(userId='me', body=rmsg).execute() except Exception as e: log.exception('sending Gmail message failed')
def _send(self, user_id: str, msg: MIMEBase) -> dict: """Send composed email through API. :param user_id: displayed user id. :param msg: A composed MIMEBase object. :return: dictionary of response """ body = { 'raw': urlsafe_b64encode(msg.as_bytes()).decode(), 'payload': { 'mimeType': 'text/html' } } response = self._service.send(userId=user_id, body=body).execute() logging.debug(response) return response
def add_dkim_sig_to_message(msg: MIMEBase, dkim_obj: DKIM) -> None: if dkim is None: raise RuntimeError("dkim package not installed") # Based on example from: # https://github.com/russellballestrini/russell.ballestrini.net/blob/master/content/ # 2018-06-04-quickstart-to-dkim-sign-email-with-python.rst sig = dkim.sign( message=msg.as_bytes(), selector=dkim_obj.selector, domain=dkim_obj.domain, privkey=dkim_obj.private_key, include_headers=dkim_obj.include_headers, ) # add the dkim signature to the email message headers. # decode the signature back to string_type because later on # the call to msg.as_string() performs it's own bytes encoding... msg["DKIM-Signature"] = sig[len("DKIM-Signature: "):].decode()