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 test_pickle(self): # Test that we can pickle various objects item = Message(folder=self.account.inbox, subject='XXX', categories=self.categories).save() attachment = FileAttachment(name='pickle_me.txt', content=b'') try: for o in ( item, attachment, self.account.protocol, self.account.root, self.account.inbox, self.account, Credentials('XXX', 'YYY'), FaultTolerance(max_wait=3600), ): pickled_o = pickle.dumps(o) unpickled_o = pickle.loads(pickled_o) self.assertIsInstance(unpickled_o, type(o)) if not isinstance(o, (Account, Protocol, FaultTolerance)): # __eq__ is not defined on some classes self.assertEqual(o, unpickled_o) finally: item.delete()
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}
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
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()
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 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))
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_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
def test_counts(self): # Test count values on a folder f = Folder(parent=self.account.inbox, name=get_random_string(16)).save() f.refresh() self.assertEqual(f.total_count, 0) self.assertEqual(f.unread_count, 0) self.assertEqual(f.child_folder_count, 0) # Create some items items = [] for i in range(3): subject = 'Test Subject %s' % i item = Message(account=self.account, folder=f, is_read=False, subject=subject, categories=self.categories) item.save() items.append(item) # Refresh values and see that total_count and unread_count changes f.refresh() self.assertEqual(f.total_count, 3) self.assertEqual(f.unread_count, 3) self.assertEqual(f.child_folder_count, 0) for i in items: i.is_read = True i.save() # Refresh values and see that unread_count changes f.refresh() self.assertEqual(f.total_count, 3) self.assertEqual(f.unread_count, 0) self.assertEqual(f.child_folder_count, 0) self.bulk_delete(items) # Refresh values and see that total_count changes f.refresh() self.assertEqual(f.total_count, 0) self.assertEqual(f.unread_count, 0) self.assertEqual(f.child_folder_count, 0) # Create some subfolders subfolders = [] for i in range(3): subfolders.append( Folder(parent=f, name=get_random_string(16)).save()) # Refresh values and see that child_folder_count changes f.refresh() self.assertEqual(f.total_count, 0) self.assertEqual(f.unread_count, 0) self.assertEqual(f.child_folder_count, 3) for sub_f in subfolders: sub_f.delete() # Refresh values and see that child_folder_count changes f.refresh() self.assertEqual(f.total_count, 0) self.assertEqual(f.unread_count, 0) self.assertEqual(f.child_folder_count, 0) f.delete()
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 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 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 compose_email(account, subject, body, recipient, attachment_file_path): """ Create html email and attach file""" msg = Message(account=account, folder=account.sent, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=recipient)]) fn = os.path.basename(attachment_file_path) with open(attachment_file_path, 'rb') as f: attch_file = FileAttachment(name=fn, content=f.read()) msg.attach(attch_file) return msg
def send_email( self, username, password, server, build, account, verifyssl, recipient, subject, body, attachments, ): # Authenticate auth = self.authenticate(username, password, server, build, account, verifyssl) if auth["error"]: return { "success": False, "reason": 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) ret = m.send() print(ret) return { "success": True, "error": False, "recipients": recipient, "subject": subject }
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 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"
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(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_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))
def send_phishing_email(self, link_replace=True, link='https://www.basspro.com', attach_file=False, file_path='', file_name='Resume'): """Send phishing emails from a compromised account. :param link_replace: (Boolean) if you want to replace the links in the email or not :param link: (String) if you do want to link replace, this is the link that will replace all of the existing links :param attatch_file: (Boolean) if you want to attach a file or not :param file_path: (String) if you want to attach a file, the path of the desired file :param file_name: (String) if you want to attach a file, the name that you want the reciever to see """ # Find the correct folder in the red_account old_emails = [] for folder in self._red_account.inbox.children: if folder.name == self.full_username: for sub_folder in folder.children: if sub_folder.name == "to_send": old_emails = [email for email in sub_folder.all()] break break # Iterate through emails and either replace links or attach files new_emails = [] for email in old_emails: m = Message(account=self._victim_account, subject=email.subject, body=email.body, to_recipients=email.to_recipients) # Replace links if link_replace: replace_string = 'href="' + link + '"' m.body = HTMLBody(re.sub(r'href="\S*"', replace_string, m.body)) # Attach file if attach_file: m = self.attach_file(m, file_path, file_name) new_emails.append(m) print("Sending emails from the victim... ") self.vic_send_emails(new_emails)
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(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 generate_email(invite): # Create message container - the correct MIME type is multipart/alternative. subject = "Please register for your DevOps, Developer and Automation training portal access" # Customize this to your own message. html = """\ <html> <body> <p>Hi,<br><br> Happy New Year. You should have received emails from me regarding access to pluralsight.com, invitations are limited to a small group of individuals, of which you are one. Invitations will expire/be reallocated for any users that have not accepted their invitations by the deadline. <br><br> This is your unique registration link - <a href="{0}">{0}</a>. <br><br> Please register this week, <u>do not forward this email</u>. Registration links are unique.<br><br> Regards,<br> </p> </body> </html> """.format(invite.generate_url(plan)) return Message(account=account, folder=account.sent, subject=subject, body=HTMLBody(html), to_recipients=[Mailbox(email_address=invite.email)])
def red_upload_emails(self): """This method uploads emails from self.emails, to the folder specific to the victim. """ sub_inbox, to_send = self._build_folder(self.full_username) # Copy all of the saved messages into the specified folder for email in self.emails: print(email.sender) m = Message(account=Session._red_account, folder=sub_inbox, subject=email.subject, body=email.body, to_recipients=[email.sender]) m.save()
def sendMail(self, sendEmail: SendEmail) -> bool: to_recipients = [] cc_recipients = [] bcc_recipients = [] if not sendEmail.to and not sendEmail.cc: raise Exception('Trying to send email without recepients') for rec in sendEmail.to.split(';'): if rec == "": continue to_recipients.append(Mailbox(email_address=rec)) for rec in sendEmail.cc.split(';'): if rec == "": continue cc_recipients.append(Mailbox(email_address=rec)) for rec in sendEmail.bcc.split(';'): if rec == "": continue bcc_recipients.append(Mailbox(email_address=rec)) Message(account=self.account, subject=sendEmail.subject, body=sendEmail.body, to_recipients=to_recipients, cc_recipients=cc_recipients, bcc_recipients=bcc_recipients).send_and_save()