def sendEmail(): ''' function to send email with the zip file as attachment ''' m = Message( account=a, subject='AUTOMATED DISCOUNT OVERLAP REPORT ' + str(today), body = HTMLBody("Dear ALL, <br/><br/> Please find attached report. <br/><br/>The report is also accessible at the following address: <br/><a style='color:blue; text-decoration:underline'>link here</a> "), to_recipients=[ Mailbox(email_address='*****@*****.**') ], cc_recipients=['*****@*****.**'], # Simple strings work, too # bcc_recipients=[ # Mailbox(email_address='*****@*****.**'), # '*****@*****.**', #], # Or a mix of both ) attachments=[] with open(str(getFile('.zip')) + '.zip', 'rb') as f: content = f.read() attachments.append((str(getFile('.zip')) + '.zip', content)) for attachment_name, attachment_content in attachments: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send_and_save()
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
def notifyOfChange(self): # format message body into something useful messageGreeting = '' today = str(date.today()) # check to see if the application was a pass or a fail if self.passFail == True: messageGreeting = "Below are the stations that have received new check-ins: \n" formattedMessage = '' for ind in self.updateMessage: formattedMessage += str(ind + '\n') else: messageGreeting = "Station: The following station was unable to scrape. Please check the URL " \ "for any discrepencies: \n" formattedMessage = "Station {0},\n URL https://www.plugshare.com/location/{1}".format( self.stationNames, self.urlID) # set exchange credentials credentials = Credentials('<UserName>', '<Password>') account = Account("<Outlook Email Address>", credentials=credentials, autodiscover=True, access_type=DELEGATE) recipients = ['<Email Addresses>'] #create message testMessage = Message( account=account, folder=account.sent, subject='{0} Plugshare Report (auto-generated)'.format(today), body="{0}{1}".format(messageGreeting, formattedMessage), to_recipients=recipients) testMessage.send_and_save()
def send(self, to, body): m = Message(account=self.account, folder=self.account.sent, subject="Personal tutor attendance data", body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)]) m.send_and_save()
def send_email(subject, body, recipients, attachments=None): """ Send an email. Parameters ---------- account : Account object subject : str body : str recipients : list of str Each str is and email adress attachments : list of tuples or None (filename, binary contents) 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, folder=account.sent, subject=subject, body=body, to_recipients=to_recipients) # attach files for attachment_name, attachment_content in attachments or []: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send_and_save()
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()
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
def ews_send_email(ews_account, subject, body, recipient, attachments=None): ''' Email -> Recipient Attachments are python dictionary {FileName : FileContent} Moves the sent email into the 'Outbound' folder ''' try: # Setup empty dict if attachments is None: attachments = [] # Prep email message email_draft = Message(account=ews_account, folder=ews_account.inbox / 'Outbound', subject=subject, body=body, to_recipients=[Mailbox(email_address=recipient)]) for dict_key in attachments: attachment = FileAttachment(name=dict_key, content=attachments[dict_key]) email_draft.attach(attachment) # Send the Email email_draft.send_and_save() # Mark the sent email as unread ews_toggle_is_read(ews_account, 'Outbound') except Exception as error_text: print(f'[Error] Unable to send email - {str(error_text)}') sys.exit()
def send_mail_exchange(config, recipients, subject, body, attachments): """Sends the supplied message through an Exchange connection to the list of recipients""" # Gathering email account details user = config["Email"] password = encryption.get_password() # Connecting to Exchange account account = None try: credentials = Credentials(user, password) account = Account(user, credentials=credentials, autodiscover=True) logger.debug("Exchange connection successful") except Exception as e: logger.error("Could not connect to Exchange Email: " + str(e)) return # Constructing message message = Message(account=account, subject=subject, body=body, to_recipients=recipients.replace(", ", ",").split(",")) # Attaching files for image_path in attachments: with open(image_path, 'rb') as f: repImage = FileAttachment(name=os.path.basename(image_path), content=f.read()) message.attach(repImage) # Sending message.send_and_save()
def bulk_send_exchange_email(from_addr: str, sub: str, account: str, pwd: str, user_name: str, names_list: str, content_file: str, sheet: str, signature: str): """ Sends email using Exchange :param from_addr: :param sub: :param account: :param pwd: :param user_name: :param content_file: :param names_list: :param sheet: :param signature: :return: """ recipients = spreadsheet_data(names_list, sheet) body = content_from_file(content_file) signature = content_from_file(signature) creds = Credentials(user_name, pwd) config = Configuration(server=account, credentials=creds) account = Account(primary_smtp_address=from_addr, autodiscover=False, access_type=DELEGATE, config=config) for item in recipients: complete_email = 'Hello ' + item['First_Name'] + '\n\n' + body + '\n' + signature email_address = item['Email_Address'] msg = Message( account=account, folder=account.sent, subject=sub, body=complete_email, to_recipients=[Mailbox(email_address=email_address)]) msg.send_and_save()
def send_exchange_email(from_addr: str, to_addr: str, sub: str, body: str, account: str, pwd: str, user_name: str): """ Sends email using Exchange :param from_addr: :param to_addr: :param sub: :param body: :param account: :param pwd: :param user_name: :return: """ creds = Credentials(user_name, pwd) config = Configuration(server=account, credentials=creds) account = Account(primary_smtp_address=from_addr, autodiscover=False, access_type=DELEGATE, config=config) msg = Message( account=account, folder=account.sent, subject=sub, body=body, to_recipients=[Mailbox(email_address=to_addr)]) msg.send_and_save()
def get_ips_and_send_scanmail(task, task_1, task_2): list_name_id = get_sysinfo() id = list_name_id[task] email_address = get_user_mail(id) now = datetime.datetime.now() + datetime.timedelta(1) now = now.strftime("%Y年%m月%d日") the_system = task with open(task, "a+") as f: if (os.path.exists(task_1)): with open(task_1, "r+") as f1: f.write(f1.read()) if (os.path.exists(task_2)): with open(task_2, "r+") as f2: f.write(f2.read()) with open(task, "r+") as f: data_r = """ <table border="1" cellspacing=0> <tr> <th>系统</th> <th>资产</th> </tr>\r\n """ ips = f.readlines() for ip in ips: sytem_info = "ceshi" ip = ip.replace("\n", "") data_cow = "<tr>\r\n" + "<td>" + task + "</td>\r\n" + "<td>" + ip + "</td>" + "\r\n</tr>" data_r = data_r + data_cow data_r = data_r + "\r\n</table>" print(data_r) data = f""" <br> 您好, <br> 我方将于今晚凌晨12点对以下系统进行漏洞扫描,开展扫描工作事项如下: <br><b> 1、扫描对象:</b> <br> {the_system} <br><b> 2、扫描时间:</b> <br> {now}凌晨0:00至{now}早上8:30 <br><b style="background-color: rgb(255,255,0)"> 3、注意事项:</b> <br> a、对于扫描的系统是否有扫描时间要求。 <br> b、<t style="background-color: rgb(255,255,0);color:red">对漏洞扫描资产是否有需要剔除、确认系统资产是否有误。</t> <br> 附:可能受影响出现的情况 : <br> 有可能会对被测网络设备或主机造成异常运行; <br> 有可能会对被测主机上的各种服务和应用程序造成异常运行; <br> 扫描期间,被测主机上的各种服务的运行速度可能会减慢; <br> 扫描期间,网络的处理能力和传输速度可能会减慢; <br> <br> 详细资产请参考以下IP: <br> {data_r} <br> <br> 如发现异常,请及时联系 <br> ************************** <br> ********** """ m = Message(account=account, subject=str(today) + task + "扫描通知", body=HTMLBody(data), to_recipients=[Mailbox(email_address=email_address[0])], cc_recipients=["**********", "**********"]) m.send_and_save() return
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
def sendMessage(recipient, subject, body): try: m = Message(account=account, folder=account.sent, subject=subject, body=body, to_recipients=[Mailbox(email_address=recipient)]) except Exception as e: print("\nfailed sending email.\n", str(e)) m.send_and_save()
def Email(subject, body, to, cc=None): m = Message(account=account, subject=subject, body=body, to_recipients=[Mailbox(email_address=to)], cc_recipients=[Mailbox(email_address=cc)]) # 附件加"rb" cont = open(excelName, 'rb').read() attach = FileAttachment(name=excelName, content=cont) m.attach(attach) m.send_and_save()
def send_email(to_email, subject, message): """Send E-mail via MS Exchange Server using credentials from env vars Parameters ---------- to_email : :obj:`str` Target mail address subject : :obj:`str` Subject of mail message : :obj:`str` Message body of mail Returns ------- :obj:`bool` Success status (True: successful) """ credentials = Credentials(WAM_EXCHANGE_ACCOUNT, WAM_EXCHANGE_PW) try: account = Account(WAM_EXCHANGE_EMAIL, credentials=credentials, autodiscover=True) except ConnectionError: err_msg = "Feedback-Form - Verbindungsfehler!" logging.error(err_msg) return False except AutoDiscoverFailed: err_msg = "Feedback-Form - Konto- oder Authentifizierungsfehler!" logging.error(err_msg) return False except Exception as err: # pylint: disable=broad-except err_msg = f"Feedback-Form - Sonstiger Fehler: {err}" logging.error(err_msg) return False recipients = [Mailbox(email_address=to_email)] m = Message( account=account, folder=account.sent, subject=subject, body=message, to_recipients=recipients, ) try: m.send_and_save() except Exception as err: # pylint: disable=broad-except err_msg = f"Feedback-Form - Fehler beim Mailversand: {err}" logging.error(err_msg) return False return True
def sendEmailExhange(userName,password,fromEmail,toEmail,msgSubject,msgText): credentials = Credentials(userName,password) account = Account(fromEmail, credentials=credentials, autodiscover=True) m = Message( account=account, folder=account.sent, subject=msgSubject, body=msgText, to_recipients=[Mailbox(email_address=toEmail)] ) m.send_and_save() print("Sent email to " + toEmail)
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
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
def send_email(self, to: [str], subject: str, body: str): # pylint: disable=C0103 """ Sends an E-Mail via Exchange Server """ to_recipients = [] for recipient in to: to_recipients.append(Mailbox(email_address=recipient)) email_message = Message(account=self.account, folder=self.account.sent, subject=subject, body=body, to_recipients=to_recipients) email_message.send_and_save()
def process_cc(itemsToProcess, ccfolder): for item in itemsToProcess: print(item.author.email_address, " - ", item.subject, ": sending warning back to sender.") # need to reply, but also move... m = Message( account=account, folder=account.sent, subject='Regarding your email: ' + item.subject, body=messageToSend, to_recipients=[Mailbox(email_address=item.author.email_address)]) m.send_and_save() item.move(to_folder=ccfolder)
def _send_email( self, account, subject, body, recipients, attachments: [Attachment] = None, reply_to: [str] = [], ): """ Send an email. Parameters ---------- account : Account object subject : str body : str recipients : list of str Each str is and email adress attachments : list of tuples or None (filename, binary contents) Examples -------- >>> send_email(account, 'Subject line', 'Hello!', ['*****@*****.**']) """ to_recipients = [] for recipient in recipients: to_recipients.append(Mailbox(email_address=recipient)) reply_to_addresses = [] for address in reply_to: reply_to_addresses.append(Mailbox(email_address=address)) m = Message( account=account, folder=account.sent, subject=subject, body=HTMLBody(body), to_recipients=to_recipients, reply_to=reply_to, ) # attach files for attachment in attachments or []: file = FileAttachment(name=attachment.file_name, content=attachment.content) m.attach(file) logging.info("Sending mail to {}".format(to_recipients)) m.send_and_save()
def send_email(self, to_address, subject, body, cc_recipients=[]): """ Send a trial or pending email based on the club """ # Build and send message msg = Message( account=self.account, folder=self.account.sent, subject=subject, body= HTMLBody(body), to_recipients=[Mailbox(email_address=to_address)], cc_recipients=[(Mailbox(email_address=x)) for x in cc_recipients] ) msg.send_and_save() print("Message to {} sent.".format(to_address))
def sendEmail(to, subject, body): BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter creds = Credentials(username='******', password='******') config = Configuration(server='rndcas.h3c.com', credentials=creds, auth_type=NTLM) account = Account(primary_smtp_address=SENDER, config=config, autodiscover=False, access_type=DELEGATE) m = Message(account=account, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)]) m.send_and_save()
def send_email(account, subject, body, recipients, attachments): to_recipients = [] for recipient in recipients: to_recipients.append(Mailbox(email_address=recipient)) # Create message m = Message(account=account, folder=account.sent, subject=subject, body=body, to_recipients=to_recipients) # attach files #for attachment_name, attachment_content in attachments or []: file = FileAttachment(name='Code', content=f) m.attach(file) m.send_and_save()
def send_bug_report(subject, message): """Send Bug-Report via MS Exchange Server""" account = get_exchange_account() recipients = [ Mailbox(email_address=recipient) for recipient in settings.BUG_RECIPIENTS ] try: m = Message( account=account, folder=account.sent, subject=subject, body=message, to_recipients=recipients, ) m.send_and_save() except Exception as e: logging.error(e)
def send_email(account, subject, body, recipients, attachments=None): to_recipients = [] for recipient in recipients: to_recipients.append(Mailbox(email_address=recipient)) #####Create message##### m = Message(account=account, folder=account.sent, subject=subject, body=body, to_recipients=to_recipients) #####attach files##### for attachment_name, attachment_content in attachments or []: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send_and_save() logger.info("Email sent successfully")
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): print('Receiving message from:', peer) print('Message addressed from:', mailfrom) print('Message addressed to :', rcpttos) print('Message length :', len(data)) self._save_message(data) msg = email.message_from_bytes(data) if msg.is_multipart(): print("multipart mail, ignored!") else: subject = decode_mime_words(msg.get('subject', '')) body = msg.get_payload(decode=True).decode('utf8') charset = msg.get_content_charset() content_encoding = msg.get('content-transfer-encoding', '') content_type = msg.get_content_type() print('Message subject :', subject) print("orig subject=", msg.get('subject', '')) print('Message charset :', charset) print('Message encoding :', content_encoding) print('Message type :', content_type) # now to EWS ... if is_probably_html(body, content_type): body = HTMLBody(body) recipients = [Mailbox(email_address=r) for r in rcpttos] m = Message( account=self.account, folder=self.account.sent, subject=subject, body=body, to_recipients=recipients ) m.send_and_save() print("mail sent via Exchange")
def main(argv): args = setup_cmdline_parser() assert args.config_file is not None if not os.path.exists(args.config_file): print('Config file {} not found!'.format(args.config_file)) sys.exit(-1) with open(args.config_file) as json_file: data = json.load(json_file) username = data['username'] password = data['password'] email = data['email'] credentials = Credentials(username=username, password=password) a = Account(primary_smtp_address=email, credentials=credentials, autodiscover=True, access_type=DELEGATE) a.root.refresh() some_folder = a.root / 'Top of Information Store' / 'Sent Items' / 'Automatic' if not os.path.exists(args.student_link_file): print("File {} does not exist!".format(args.student_link_file)) students = pickle.load(open(args.student_link_file, "rb")) for i, (k, v) in enumerate(students.items()): print("Sending {} to {} {} ({})".format(v['read_only_link'], v['Vorname'], v['Nachname'], v['group'])) m = Message( account=a, folder=some_folder, subject=args.subject, body="({} {}): The read-only link (for review) is {}".format( v['Vorname'], v['Nachname'], v['read_only_link']), to_recipients=[Mailbox(email_address=v['email'])]) m.send_and_save()
def mail_send(name_user, mail_address): mail_address = mail_address.replace("['", "") mail_address = mail_address.replace("']", "") data = mail_body(name_user) mail_Data = data[0] is_send = int(data[1]) if is_send == 0: file = name_user.replace(".xls", "") now = datetime.datetime.now() the_time = now.strftime('%Y' + "年" + '%m' + "月" + '%d' + "日") m = Message(account=account, subject=the_time + file + "现存漏洞清单", body=HTMLBody(mail_Data), to_recipients=[Mailbox(email_address=mail_address)], cc_recipients=["**********", "**********"]) with open(name_user, "rb") as f: conf = f.read() attch = FileAttachment(name=name_user, content=conf) m.attach(attch) m.send_and_save() else: pass return