示例#1
0
def send_email_to_mailbox(account,
                          to,
                          subject,
                          body,
                          bcc=None,
                          cc=None,
                          reply_to=None,
                          html_body=None,
                          attachments=[]):
    message_body = HTMLBody(html_body) if html_body else body
    m = Message(account=account,
                folder=account.sent,
                cc_recipients=cc,
                bcc_recipients=bcc,
                subject=subject,
                body=message_body,
                to_recipients=to,
                reply_to=reply_to)
    if account.protocol.version.build <= EXCHANGE_2010_SP2:
        m.save()
        for attachment in attachments:
            m.attach(attachment)
        m.send()
    else:
        for attachment in attachments:
            m.attach(attachment)
        m.send_and_save()
    return m
示例#2
0
def send_email(content, exchange_host, mailbox, mail_user, mail_password,
               dest_address):
    """
    Sends an email to dest_address containing the list of potential malicious new domains.
    """
    from exchangelib import DELEGATE, Account, Configuration, Credentials, Message, Mailbox

    message = "Found the following potential malicious new domains: {}".format(
        content)

    creds = Credentials(username=mail_user, password=mail_password)
    serverconfig = Configuration(server=exchange_host, credentials=creds)
    account = Account(primary_smtp_address=mailbox,
                      credentials=creds,
                      autodiscover=False,
                      config=serverconfig,
                      access_type=DELEGATE)

    if account:
        print("Authenticated as {} to O365 succeeded.".format(mail_user))
    else:
        print("Authentication to O365 mailbox as {} has failed.".format(
            mail_user))
        sys.exit(-1)

    m = Message(account=account,
                subject='New domain alert',
                body=message,
                to_recipients=[
                    Mailbox(email_address=dest_address),
                ])
    m.send()

    print("Email has been sent to {}.".format(dest_address))
示例#3
0
def email(report_path, attachment):
    html_report_path = os.path.join(report_path, attachment)

    content = open(html_report_path, 'rb').read()
    credentials = Credentials('*****@*****.**', 'Jt123456')
    account = Account('*****@*****.**',
                      credentials=credentials,
                      autodiscover=True)

    item = Message(
        account=account,
        subject="{} Automation Report".format(
            datetime.datetime.now().strftime('%Y-%m-%d-%H')),
        body=HTMLBody(
            'This is an automation run result report email. Please do not reply.*'
        ),
        to_recipients=[
            Mailbox(email_address='*****@*****.**'),
            Mailbox(email_address='*****@*****.**'),
            Mailbox(email_address='*****@*****.**'),
        ],
    )

    my_file = FileAttachment(name=attachment, content=content)
    item.attach(my_file)
    item.send()
示例#4
0
 def send_messages(self, email_messages):
     """
     This function send messages
     :param email_messages: list or tuple of messages
     :return: amount of messages have sent
     """
     if not email_messages:
         return 0
     with self._lock:
         self.open(
         )  # if connection exists open() will do nothing, else it'll open connection
         if self.connection is None:
             return 0  # failed to connect
         # credentials = Credentials(settings.EMAIL_USER, settings.EMAIL_PASSWORD)
         # account = Account(settings.EMAIL_ACCOUNT, credentials=credentials, autodiscover=True)
         count = 0
         for m in email_messages:
             try:
                 message = Message(account=self.connection,
                                   subject=m.subject,
                                   body=m.body,
                                   to_recipients=m.to,
                                   cc_recipients=m.cc)
                 message.send()
                 count += 1
             except Exception as e:
                 if not self.fail_silently:
                     raise e
         return count
示例#5
0
def send_smtp(self, attachment=None):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = self.subject
    msg['To'] = self.to_field
    msg['From'] = self.from_field

    logger.debug(print(
        'the html_body is a ' + type(self.html_body) + ' datatype.'
        )

    part2 = MIMEText(self.html_body, 'html')
    msg.attach(part2)

    try:
        mail = smtplib.SMTP('smtp.gmail.com', 587)
        mail.ehlo()
        mail.starttls()

        mail.login(self.secrets['username'], self.secrets['password'])
        mail.sendmail(self.from_address, self.from_address,
                        msg.as_string())
        mail.quit()
        logger.info(f'\n--> Email sent with subject: "{self.subject}"\n')

    except:
        logger.error('Failed to connect to smtp server')

def send_exchange(self, attachment=None):
    '''
    Authenticates with exchave server and sends an email
    '''
    self.connect_to_exchange()

    m = Message(
        account=self.ews_account,
        subject=self.subject,
        body=HTMLBody(self.template.render(
            subject=self.subject, body=self.html_body)),
        to_recipients=[self.to_address],
        # defaults to sending yourself an email
        cc_recipients=[''],
        # bcc_recipients=[],
    )

    if type(attachment) is str:
        attachment_filepath = os.path.join(
            os.getcwd(), attachment)
        with open(attachment_filepath, 'rb') as f:
            binary_file_content = f.read()

        logger.info(f'Attaching {attachment} to the report')
        m.attach(FileAttachment(name=attachment,
                                content=binary_file_content))

    if self.images:
        self.attach_images()

    m.send()

    logger.info(f'--> Email sent with subject: "{self.subject}"')
def Email(self,to, subject, body,email_type, attachments=None):
    creds = Credentials(username=self.localVariable["__EMAILEX__"],
                        password=self.localVariable["__EMAILEX_PASSWORD__"])
    config = Configuration(server='outlook.office365.com',credentials=creds)
    account = Account(
        primary_smtp_address=self.localVariable["__EMAILEX__"],
        config=config,
        # credentials=creds,
        autodiscover=False,
        access_type=DELEGATE
    )
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients = [Mailbox(email_address=to)]
    )
    if attachments:
        m.attach(attachments)
    if email_type==1 and to in list(self.localStore.keys()):
        print("清除 %s" % to)
        self.localStore.pop(to)
    try:
        m.send()
        if email_type == 0:
            message = u"验证码已发送邮箱!"
        else:
            message = u"证书已发送邮箱!"
        return message
    except:
        message = u"发送失败!"
        return message
示例#7
0
    async def send_email(
        self,
        username,
        password,
        server,
        build,
        account,
        verifyssl,
        recipient,
        subject,
        body,
    ):
        # Authenticate
        auth = await self.authenticate(username, password, server, build,
                                       account, verifyssl)
        if auth["error"]:
            return auth["error"]
        account = auth["account"]

        m = Message(
            account=account,
            subject=subject,
            body=body,
            to_recipients=[
                Mailbox(email_address=address)
                for address in recipient.split(", ")
            ],
        )
        m.send()
        return {"ok": True, "error": False}
示例#8
0
def send_with_exchange(username, password, server, address, content,
                       subject='', to_recipients=[], attachements=[]):
    credentials = Credentials(username=username, password=password)
    config = Configuration(server=server, credentials=credentials)
    account = Account(
        primary_smtp_address=address,
        autodiscover=False,
        config=config,
        credentials=credentials,
        access_type=DELEGATE)

    _to_recipients = []
    for item in to_recipients:
        _to_recipients.append(Mailbox(email_address=item['email']))

    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(content),
        to_recipients=_to_recipients)

    if attachements:
        for item in attachements:
            with open(item['src'], 'rb') as f:
                img_attach = FileAttachment(name=item['name'], content=f.read())
            m.attach(img_attach)
    m.send()
示例#9
0
def send_email_to_mailbox(account,
                          to,
                          subject,
                          body,
                          bcc=None,
                          cc=None,
                          reply_to=None,
                          html_body=None,
                          attachments=[],
                          raw_message=None,
                          from_address=None):
    message_body = HTMLBody(html_body) if html_body else body
    m = Message(
        account=account,
        mime_content=raw_message.encode('UTF-8') if raw_message else None,
        folder=account.sent,
        cc_recipients=cc,
        bcc_recipients=bcc,
        subject=subject,
        body=message_body,
        to_recipients=to,
        reply_to=reply_to,
        author=from_address)
    if account.protocol.version.build <= EXCHANGE_2010_SP2:
        m.save()
        for attachment in attachments:
            m.attach(attachment)
        m.send()
    else:
        for attachment in attachments:
            m.attach(attachment)
        m.send_and_save()
    return m
示例#10
0
def send_email(title='报警邮件',
               recervers='*****@*****.**',
               msg='content',
               file_name=''):
    try:
        credentials = Credentials(username, password)
        config = Configuration(server=r_server, credentials=credentials)
        account = Account(username,
                          autodiscover=False,
                          config=config,
                          access_type=DELEGATE)

    except Exception as e:
        print('错误: {0}'.format(e))
        sys.exit(1)

    m = Message(
        account=account,
        subject=title,
        body=HTMLBody(msg),
        to_recipients=[Mailbox(email_address=x) for x in recervers.split(',')])
    if file_name:
        with open(os.path.abspath(r"../work_flow/sre.xls"), "rb") as f:
            cont = f.read()
        attchF = FileAttachment(name='值班表.xls', content=cont)
        m.attach(attchF)
        m.send_and_save()
    else:
        m.send()
示例#11
0
 def _send(self, email_message):
     """A helper method that does the actual sending."""
     if not email_message.recipients():
         return False
     encoding = email_message.encoding or settings.DEFAULT_CHARSET
     from_email = sanitize_address(email_message.from_email, encoding)
     recipients = [
         sanitize_address(addr, encoding)
         for addr in email_message.recipients()
     ]
     try:
         account = Account(primary_smtp_address=from_email,
                           credentials=self.credentials,
                           autodiscover=True,
                           access_type=DELEGATE)
         exchange_message = Message(account=account,
                                    subject=email_message.subject,
                                    body=email_message.body,
                                    to_recipients=[
                                        Mailbox(email_address=recipient)
                                        for recipient in recipients
                                    ])
         exchange_message.send()
     except Exception:
         if not self.fail_silently:
             raise
         return False
     return True
示例#12
0
文件: tt_mail.py 项目: boeai/mc
    def email(self, to, subject, body):
        """
        发送邮件
        :param to: 接收人
        :param subject: 邮件主题
        :param body: 邮件内容
        :return:
        """
        creds = Credentials(
            username=self.email_name,
            password=self.email_password
        )
        account = Account(
            primary_smtp_address=self.email_name + '@taoche.com',
            credentials=creds,
            autodiscover=True,
            access_type=DELEGATE
        )
        m = Message(
            account=account,
            subject=subject,
            body=HTMLBody(body),
            to_recipients=[Mailbox(email_address=i) for i in to]

        )
        m.send()
示例#13
0
    def send_message(
        self,
        recipients: str,
        subject: str = "",
        body: str = "",
        attachments: str = None,
        html: bool = False,
        images: str = None,
        cc: str = None,
        bcc: str = None,
        save: bool = False,
    ):
        """Keyword for sending message through connected Exchange account.

        :param recipients: list of email addresses, defaults to []
        :param subject: message subject, defaults to ""
        :param body: message body, defaults to ""
        :param attachments: list of filepaths to attach, defaults to []
        :param html: if message content is in HTML, default `False`
        :param images: list of filepaths for inline use, defaults to []
        :param cc: list of email addresses, defaults to []
        :param bcc: list of email addresses, defaults to []
        :param save: is sent message saved to Sent messages folder or not,
            defaults to False

        Email addresses can be prefixed with ``ex:`` to indicate an Exchange
        account address.

        Recipients is a `required` parameter.
        """
        recipients, cc, bcc, attachments, images = self._handle_message_parameters(
            recipients, cc, bcc, attachments, images
        )
        self.logger.info("Sending message to %s", ",".join(recipients))

        m = Message(
            account=self.account,
            subject=subject,
            body=body,
            to_recipients=recipients,
            cc_recipients=cc,
            bcc_recipients=bcc,
        )

        self._add_attachments_to_msg(attachments, m)
        self._add_images_inline_to_msg(images, html, body, m)

        if html:
            m.body = HTMLBody(body)
        else:
            m.body = body

        if save:
            m.folder = self.account.sent
            m.send_and_save()
        else:
            m.send()
        return True
示例#14
0
	def sendMessage(self, to, subject, body, attachmentBytes=None, attachmentName="file.txt"):
		if self.account is not None:
			self.lock.acquire()
			m = Message(account=self.account, to_recipients=[Mailbox(email_address=to.strip())], subject=subject.strip(), body=HTMLBody(body))
			if attachmentBytes is not None:
				f = FileAttachment(name=attachmentName, content=attachmentBytes)
				m.attach(f)
			m.send()
			self.lock.release()
示例#15
0
    def run(self, subject, body, to_recipients, store):
        rcpts = [Mailbox(email_address=rcpt) for rcpt in to_recipients]
        mail = Message(account=self.account,
                       subject=subject,
                       body=body,
                       to_recipients=rcpts)

        if store:
            mail.send_and_save()  # Save in Sent folder
        else:
            mail.send()
        return mail
示例#16
0
def send_email_to_mailbox(account: Account,
                          to: List[str],
                          subject: str,
                          body: str,
                          bcc: List[str],
                          cc: List[str],
                          reply_to: List[str],
                          html_body: Optional[str] = None,
                          attachments: Optional[List[str]] = None,
                          raw_message: Optional[str] = None,
                          from_address: Optional[str] = None):
    """
    Send an email to a mailbox.

    Args:
        account (Account): account from which to send an email.
        to (list[str]): a list of emails to send an email.
        subject (str): subject of the mail.
        body (str): body of the email.
        reply_to (list[str]): list of emails of which to reply to from the sent email.
        bcc (list[str]): list of email addresses for the 'bcc' field.
        cc (list[str]): list of email addresses for the 'cc' field.
        html_body (str): HTML formatted content (body) of the email to be sent. This argument
            overrides the "body" argument.
        attachments (list[str]): list of names of attachments to send.
        raw_message (str): Raw email message from MimeContent type.
        from_address (str): the email address from which to reply.
    """
    if not attachments:
        attachments = []
    message_body = HTMLBody(html_body) if html_body else body
    m = Message(
        account=account,
        mime_content=raw_message.encode('UTF-8') if raw_message else None,
        folder=account.sent,
        cc_recipients=cc,
        bcc_recipients=bcc,
        subject=subject,
        body=message_body,
        to_recipients=to,
        reply_to=reply_to,
        author=from_address)
    if account.protocol.version.build <= EXCHANGE_2010_SP2:
        m.save()
        for attachment in attachments:
            m.attach(attachment)
        m.send()
    else:
        for attachment in attachments:
            m.attach(attachment)
        m.send_and_save()
    return m
示例#17
0
def send_email(email_id):
    try:
        print("Sending Email")
        m = Message(
            account=account,
            subject='Not complying Mask Protocol',
            body=
            'This is an auto generated mail. Please do not reply\n\nYou have not follwed the mask protocol, you were found not wearing the mask.\nPlease ensure you wear the mask when entering the premises.',
            to_recipients=[Mailbox(email_address=email_id)])
        m.send()
    except:
        pass
    return "Done"
示例#18
0
    def send_mail(self, account, mailbody, recipient="*****@*****.**"):

        if not self.authenticated:
            raise EWSLoginError("Error - not authenticated. Call EWShandler.authenticate first")

        m = Message(
            account=account,
            subject="[AUTOGENERATED] From Act-On to SuperOffice",
            body=mailbody,
            to_recipients=[Mailbox(email_address=recipient)]
        )
        logging.info("E-mail message created")
        m.send()
        logging.info("E-mail sent to {0} ".format(recipient))
示例#19
0
def Email(to, subject, body):
    creds = Credentials(username=sender, password=password)
    account = Account(primary_smtp_address='*****@*****.**',
                      credentials=creds,
                      autodiscover=True,
                      access_type=DELEGATE)
    m = Message(account=account,
                subject=subject,
                body=HTMLBody(body),
                to_recipients=[Mailbox(email_address=to)])
    try:
        m.send()
        print("send ok")
    except Exception as e:
        print(e)
def send_email(account, email_message_dict, attachments, message_uuid,
               dry_run):
    logging.debug(f"Saving {message_uuid}.json to Minio")
    with tempfile.TemporaryDirectory() as tempdir:
        local_path = os.path.join(tempdir, f"{message_uuid}.json")
        with open(local_path, "w") as message_file:
            json.dump(email_message_dict, message_file)

        minio_utils.file_to_minio(
            filename=local_path,
            minio_bucket=EMAILS_BUCKET,
            minio_key=secrets["minio"]["edge"]["access"],
            minio_secret=secrets["minio"]["edge"]["secret"],
            data_classification=EDGE_CLASSIFICATION,
        )

    message = Message(account=account, **email_message_dict)

    logging.debug("Attaching logo")
    logo_path = os.path.join(RESOURCES_PATH, CITY_LOGO_FILENAME)
    with open(logo_path, "rb") as logo_file:
        message.attach(
            FileAttachment(name=CITY_LOGO_FILENAME, content=logo_file.read()))

    logging.debug(f"Attaching data files")
    for attachment_name, attachment_file in attachments:
        logging.debug(f"attachment_name='{attachment_name}'")
        with open(attachment_file, "rb") as plot_file:
            message.attach(
                FileAttachment(name=attachment_name, content=plot_file.read()))
    logging.debug(f"Sending {message_uuid} email")

    # Turning down various exchange loggers for the send - they're a bit noisy
    exchangelib_loggers = [
        logging.getLogger(name) for name in logging.root.manager.loggerDict
        if name.startswith("exchangelib")
    ]
    for logger in exchangelib_loggers:
        logger.setLevel(logging.INFO)

    if not dry_run:
        message.send(save_copy=True)
    else:
        logging.warning("**--dry_run flag set, hence not sending emails...**")

    return True
示例#21
0
    def sendmail(self,filename):
        # 此句用来消除ssl证书错误,exchange使用自签证书需加上
        BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
        cred = Credentials(self.EmailUser, self.Password)

        mailconfig = Configuration(
            server=self.EmailServer,
            credentials=cred,
            auth_type=NTLM)
        account = Account(
            primary_smtp_address=self.sender,
            config=mailconfig,
            autodiscover=False,
            access_type=DELEGATE)
        sleep(1)
        #打开测试报告,读取报告内容
        try:
            with open(os.path.join(reportPath,filename),'rb') as f:
                fileMsg = f.read().decode('utf-8')

        except Exception as e:
            log1.exception('open or read file [%s] failed,No such file or directory: %s' %(filename, reportPath))
            raise e
        else:
            log1.info('open and read file [%s] successed!' % filename)

        #登录服务器,连接邮箱,设置邮件
        try:
            m = Message(
                account=account,
                subject="测试邮件",  # 邮件主题
                body=HTMLBody(fileMsg),
                to_recipients=self.addresser
            )
        except Exception:
            log1.exception('connect [%s] server failed or username and password incorrect!' %self.EmailServer)
        else:
            log1.info('connect [%s] server successed !' %self.EmailServer)

        #发送邮件
        try:
            m.send()
        except Exception:
            log1.exception('send mail failed !')
        else:
            log1.info('send mail successed !')
示例#22
0
def delete_malicious_email(recipient_email, attachment_name):
    # once the recipients are found we parse their mailboxes and delete the malicious email

    # Args:
    #     recipient_email (str)	: malware recipient email address
    #     attachment_name (str)	: the attachment file name to identify the malicious email

    # Returns:
    #     True is it parses the mailboxes, False if an error occurs

    # TODO:
    # 	ban the infected recipient machine with either IP or FortiClient using item.is_read

    account = Account(primary_smtp_address=recipient_email,
                      config=config,
                      autodiscover=False,
                      access_type=IMPERSONATION)
    tz = EWSTimeZone.localzone()
    right_now = tz.localize(EWSDateTime.now())
    xmin_ago = right_now - timedelta(minutes=300)

    try:
        for item in account.inbox.filter(datetime_received__gt=xmin_ago):
            for attachment in item.attachments:
                if isinstance(attachment, FileAttachment):
                    if attachment.name == attachment_name:
                        # Either delete the infected email, or move it to trash
                        #item.delete()
                        item.move_to_trash()

                        #send an alert to the recipient
                        m = Message(
                            account=account,
                            subject='FortiSIEM: You have received a Virus ' +
                            attachment_name,
                            body=
                            'The maliicous email has been deleted from your inbox, please contact your administrator for further incident response',
                            to_recipients=[
                                Mailbox(email_address=recipient_email)
                            ],
                        )
                        m.send()
        return True
    except:
        return False
示例#23
0
def send(account=account,
         subject=subject,
         body=body,
         recipients=recipients,
         attachments=[]):
    """
    Send an email.

    Parameters
    ----------
    account : Account object
    subject : str
    body : str
    recipients : list of str
        Each str is an email adress
    attachments : list of str
        Each str is a path of file

    Examples
    --------
    >>> send_email(account, 'Subject line', 'Hello!', ['*****@*****.**'])
    """
    to_recipients = []
    for recipient in recipients:
        to_recipients.append(Mailbox(email_address=recipient))
    # Create message
    m = Message(account=account,
                subject=subject,
                body=body,
                to_recipients=to_recipients)

    # Read attachment
    # attachments : list of tuples or None
    # (filename, binary contents)
    files = []
    for file in attachments:
        with open(file, 'rb') as f:
            content = f.read()
        files.append((file, content))

    # attach files
    for attachment_name, attachment_content in files or []:
        file = FileAttachment(name=attachment_name, content=attachment_content)
        m.attach(file)
    m.send()
示例#24
0
def Email(to, subject, body):
    creds = Credentials(
        username='******',
        password='******'
    )
    account = Account(
        primary_smtp_address='*****@*****.**',
        credentials=creds,
        autodiscover=True,
        access_type=DELEGATE
    )
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients=[Mailbox(email_address=to)]
    )
    m.send()
示例#25
0
def Email(to, subject, body):
    creds = Credentials(
        username='******',
        password='******'
    )
    account = Account(
        primary_smtp_address='*****@*****.**',
        credentials=creds,
        autodiscover=True,
        access_type=DELEGATE
    )
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients = [Mailbox(email_address=to)]
    )
    m.send()
示例#26
0
    def send_email(
        self, to: Union[str, List[str]], header: str, body: str, attachments: dict
    ):
        """
        This method sends an email from the login address (attribute login_address).

        Parameters
        ----------
        to: str or list
            Address or list of addresses of email recipients
        header: str
            Email header
        body: str
             Email body
        attachments: dict
            Dict containing attachment names as key and attachment file contents as values.
            Currently, the code is tested for DataFrame attachments only.
        """
        if self.sender_account is None:
            raise AttributeError(
                "To send emails, you need to specify a `sender_address` when initializing "
                "the ExchangeConnector class."
            )

        if isinstance(to, str):
            to = [to]

        # Prepare Message object
        m = Message(
            account=self.sender_account,
            subject=header,
            body=HTMLBody(body),
            to_recipients=to,
        )
        if attachments:
            for key, value in attachments.items():
                m.attach(FileAttachment(name=key, content=bytes(value, "utf-8")))

        # Send email
        m.send()
        logger.info(f"Email sent from address '{self.sender_address}'")
示例#27
0
def send_email(msg_subject, msg_body, msg_recipient_email):
    EXCHANGE_USERNAME = read_key('EXCHANGE_USERNAME')
    EXCHANGE_PASSWORD = read_key('EXCHANGE_PASSWORD')
    PRIMARY_SMTP_ADDRESS = read_key('PRIMARY_SMTP_ADDRESS')
    EXCHANGE_SERVER = read_key('EXCHANGE_SERVER')

    credentials = Credentials(username=EXCHANGE_USERNAME,
                              password=EXCHANGE_PASSWORD)
    config = Configuration(server=EXCHANGE_SERVER, credentials=credentials)
    my_account = Account(primary_smtp_address=PRIMARY_SMTP_ADDRESS,
                         config=config,
                         autodiscover=False,
                         access_type=DELEGATE)

    m = Message(account=my_account,
                subject=msg_subject,
                body=msg_body,
                to_recipients=[
                    Mailbox(email_address=msg_recipient_email),
                ])
    m.send()
示例#28
0
def EmailWarning(subject, body):
    creds = Credentials(  # 域账号和密码
        username='******', password='******')
    account = Account(  # 发送邮件的邮箱
        primary_smtp_address='@.com',
        credentials=creds,
        autodiscover=True,
        access_type=DELEGATE)
    m = Message(account=account,
                subject=subject,
                body=HTMLBody(body),
                to_recipients=[
                    Mailbox(email_address='@.com'),
                    Mailbox(email_address='@.com'),
                    Mailbox(email_address='@.com'),
                    Mailbox(email_address='@.com'),
                    Mailbox(email_address='@.com'),
                ]
                # 向指定邮箱里发预警邮件
                )
    m.send()
示例#29
0
    async def send_email(
        self,
        username,
        password,
        server,
        build,
        account,
        verifyssl,
        recipient,
        subject,
        body,
        attachments,
    ):
        # Authenticate
        auth = await self.authenticate(username, password, server, build,
                                       account, verifyssl)
        if auth["error"]:
            return auth["error"]
        account = auth["account"]

        m = Message(
            account=account,
            subject=subject,
            body=body,
            to_recipients=[
                Mailbox(email_address=address)
                for address in recipient.split(", ")
            ],
        )

        file_uids = attachments.split()
        if len(file_uids) > 0:
            for file_uid in file_uids:
                attachment_data = self.get_file(file_uid)
                file = FileAttachment(name=attachment_data["filename"],
                                      content=attachment_data["data"])
                m.attach(file)

        m.send()
        return {"ok": True, "error": False}
示例#30
0
    def sendmail(self, subject, body, filename, receiver):

        creds = Credentials(username=self.username, password=self.password)

        account = Account(primary_smtp_address=self.username,
                          credentials=creds,
                          autodiscover=True,
                          access_type=DELEGATE)
        to_recipients = []
        for to in receiver:
            to_recipients.append(Mailbox(email_address=to))

        m = Message(
            account=account,
            subject=subject,
            body=HTMLBody(body),
            to_recipients=to_recipients,
        )

        file = FileAttachment(name='Test_report.html',
                              content=open(filename, 'rb').read())
        m.attach(file)
        m.send()