jeremyephron / simplegmail

A simple Gmail API client for applications in Python
MIT License
336 stars 73 forks source link

Reply Message #72

Open devfemibadmus opened 2 years ago

devfemibadmus commented 2 years ago

give an update and add reply message

def _create_reply(
        self,
        sender: str,
        to: str,
        subject: str = '',
        msg_html: str = None,
        msg_id: int = None,
        msg_plain: str = None,
        cc: List[str] = None,
        bcc: List[str] = None,
        attachments: List[str] = None,
        signature: bool = False,
        user_id: str = 'me'
    ) -> dict:
        msg = MIMEMultipart('mixed' if attachments else 'alternative')
        msg['To'] = to
        msg['From'] = sender
        msg['Subject'] = subject
        msg["In-Reply-To"] = msg_id
        msg["References"] = msg_id

        if cc:
            msg['Cc'] = ', '.join(cc)

        if bcc:
            msg['Bcc'] = ', '.join(bcc)

        if signature:
            m = re.match(r'.+\s<(?P<addr>.+@.+\..+)>', sender)
            address = m.group('addr') if m else sender
            account_sig = self._get_alias_info(address, user_id)['signature']

            if msg_html is None:
                msg_html = ''

            msg_html += "<br /><br />" + account_sig

        attach_plain = MIMEMultipart('alternative') if attachments else msg
        attach_html = MIMEMultipart('related') if attachments else msg

        if msg_plain:
            attach_plain.attach(MIMEText(msg_plain, 'plain'))

        if msg_html:
            attach_html.attach(MIMEText(msg_html, 'html'))

        if attachments:
            attach_plain.attach(attach_html)
            msg.attach(attach_plain)

            self._ready_message_with_attachments(msg, attachments)

        return {
            'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode()
        }
def reply_message(
        self,
        sender: str,
        to: str,
        subject: str = '',
        msg_html: Optional[str] = None,
        msg_id: int = None,
        msg_plain: Optional[str] = None,
        cc: Optional[List[str]] = None,
        bcc: Optional[List[str]] = None,
        attachments: Optional[List[str]] = None,
        signature: bool = False,
        user_id: str = 'me'
    ) -> Message:
        msg = self._create_reply(
            sender, to, subject, msg_html, msg_id, msg_plain, cc=cc, bcc=bcc,
            attachments=attachments, signature=signature, user_id=user_id
        )

        try:
            req = self.service.users().messages().send(userId='me', body=msg)
            res = req.execute()
            return self._build_message_from_ref(user_id, res, 'reference')

        except HttpError as error:
            # Pass along the error
            raise error