def process(category, config): """ Process a category to produce a metadata file """ write = False message = email.message.Message() # Only write out the name if it differs from the Publ default if category.name and category.basename.title() != category.name: write = True message['Name'] = category.name # Add the description if category.description: write = True message.set_payload(category.description) if not write: LOGGER.info("Category '%s' has no vital metadata", category.path or '(root)') return output_filename = os.path.join(*category.path.split('/'), f'_{category.basename}.cat') save_file(message, config.content_dir, output_filename, config)
def sendEmail(recipient, content, config, outcome): # Create email content message = email.message.Message() message['Subject'] = 'Your daily COVID-19 report' message['From'] = config['address'] message['To'] = recipient message.add_header('Content-Type', 'text/html') message.set_payload(content) # Start server and log in to sender email server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() server.login(message['From'], config['password']) # Attempt to send email try: server.sendmail(message['From'], message['To'], message.as_string()) outcome[0] += 1 except Exception as e: print('Unable to send email to ' + recipient + '. Error: ' + str(e)) outcome[1] += 1 # Quit server server.quit()
def domain_reactive_email(domain_name): ### AWS Config ### EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 # Setup email message message = email.message.Message() message['Subject'] = "Domain Back Online" message['From'] = fromaddr message['To'] = ", ".join(toaddr) # message.add_header('Content-Type', 'text/html') error_msg = '%s is back online.' % domain_name # Add error as payload, and "stringify" content message.set_payload(error_msg) msg_full = message.as_string() # Send message s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) s.starttls() s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) s.sendmail(fromaddr, toaddr, msg_full) s.quit()
def sendMessage(fromByValue, toByValue, subject, body, headerByName=None): 'Send a message using SMTP' # Prepare message = email.message.Message() message.add_header( 'from', email.utils.formataddr( (fromByValue['nickname'], fromByValue['email']))) message.add_header( 'to', email.utils.formataddr((toByValue['nickname'], toByValue['email']))) message.add_header('subject', subject) message.set_payload(body) if headerByName: for key, value in headerByName.iteritems(): message.add_header(key, value) # Connect to server if fromByValue['smtp'] == 'localhost': server = smtplib.SMTP('localhost') else: server = smtplib.SMTP_SSL(fromByValue['smtp'], 465) if len(fromByValue['username']): server.login(fromByValue['username'], fromByValue['password']) # Send mail try: server.sendmail(fromByValue['email'], toByValue['email'], message.as_string()) except socket.error, error: raise SMTPError(error)
def test_alternate_transaction_manager(self): from repoze.sendmail.delivery import DirectMailDelivery from email.message import Message import transaction mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) tm = transaction.TransactionManager() delivery.transaction_manager = tm fromaddr = "Jim <*****@*****.**>" toaddrs = ("Guido <*****@*****.**>", "Steve <*****@*****.**>") message = Message() message["From"] = fromaddr message["To"] = ",".join(toaddrs) message["Date"] = "Date: Mon, 19 May 2003 10:17:36 -0400" message["Subject"] = "example" message.set_payload("This is just an example\n") msgid = delivery.send(fromaddr, toaddrs, message) transaction.commit() self.assertEqual(len(mailer.sent_messages), 0) t = tm.get() data_manager = t._resources[0] self.assertTrue(data_manager.transaction_manager is tm) t.commit() self.assertEqual(len(mailer.sent_messages), 1) self.assertEqual(mailer.sent_messages[0][0], fromaddr) self.assertEqual(mailer.sent_messages[0][1], toaddrs) self.assertEqual(mailer.sent_messages[0][2].get_payload(), "This is just an example\n") mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) tm.get().abort() self.assertEqual(len(mailer.sent_messages), 0)
def send_email(self, workspace, messages): '''Send an email according to the settings''' measurements = workspace.measurements assert isinstance(measurements, cpmeas.Measurements) message = email.message.Message() who_from = self.from_address.value who_to = [group.recipient.value for group in self.recipients] subject = measurements.apply_metadata(self.subject.value) message["Content-Type"] = "text/plain" message["From"] = who_from message["To"] = ",".join(who_to) message["Subject"] = subject payload = [] for msg in messages: msg = measurements.apply_metadata(msg) payload.append(msg) message.set_payload("\n".join(payload)) server = smtplib.SMTP(self.smtp_server.value, self.port.value) try: server.sendmail(who_from, who_to, message.as_string()) return message.as_string() except: logger.error("Failed to send mail", exc_info=True) return "Failed to send mail"
def send_mail(email_address, passwd, html_string, code): global debug if debug: url = "http://localhost:5000/verificacion/" + code else: url = "https://eco-asistente.herokuapp.com/verificacion/" + code print(url) #Datos de la cuenta. gmail_user = '******' gmail_password = '******' #Instanciación del objeto email.message message = email.message.Message() #Parámetros para el envío del email. sent_from = gmail_user to = [email_address] message['Subject'] = "EcoAsistente - Activá tu cuenta" #Importo el archivo html. #Formateo del email. message.add_header('Content-Type', 'text/html') message.set_payload(html_string) #Envío del email. server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, message.as_string().replace("URL_TO_REPLACE", url)) server.close()
def assemble_mail_data(self, headers, body=None): message = email.message.Message() for key, value in headers.items(): message.add_header(key, value) if body: message.set_payload(body) return message.as_bytes()
def mail_changes(config, changes, subject): ALCLog.info( _("Mailing %(address)s: %(subject)s") % { 'address': config.email_address, 'subject': subject }) charset = email.charset.Charset('utf-8') charset.body_encoding = '8bit' charset.header_encoding = email.charset.QP message = email.message.Message() if config.email_format == 'html': changes = html(config).convert_to_html(subject, changes) message['Content-Type'] = 'text/html; charset=utf-8' message['Auto-Submitted'] = 'auto-generated' message['Subject'] = email.header.Header(subject, charset) message['To'] = config.email_address message.set_payload(changes, charset) try: subprocess.run(['/usr/sbin/sendmail', '-oi', '-t'], input=message.as_bytes(), check=True) except Exception as ex: ALCLog.warning( _("Failed to send mail to %(address)s: %(errmsg)s") % { 'address': config.email_address, 'errmsg': ex })
def test_alternate_transaction_manager(self): from repoze.sendmail.delivery import DirectMailDelivery from email.message import Message import transaction mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) tm = transaction.TransactionManager() delivery.transaction_manager = tm fromaddr = "Jim <*****@*****.**>" toaddrs = ('Guido <*****@*****.**>', 'Steve <*****@*****.**>') message = Message() message["From"] = fromaddr message["To"] = ",".join(toaddrs) message["Date"] = "Date: Mon, 19 May 2003 10:17:36 -0400" message["Subject"] = "example" message.set_payload("This is just an example\n") msgid = delivery.send(fromaddr, toaddrs, message) transaction.commit() self.assertEqual(len(mailer.sent_messages), 0) t = tm.get() data_manager = t._resources[0] self.assertTrue(data_manager.transaction_manager is tm) t.commit() self.assertEqual(len(mailer.sent_messages), 1) self.assertEqual(mailer.sent_messages[0][0], fromaddr) self.assertEqual(mailer.sent_messages[0][1], toaddrs) self.assertEqual(mailer.sent_messages[0][2].get_payload(), "This is just an example\n") mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) tm.get().abort() self.assertEqual(len(mailer.sent_messages), 0)
def send_signup_email(receiver, token): try: SignUp.check_user(receiver) port = 465 # For SSL sender, password = EMAIL, PASSWORD signup_url = SIGNUP_URL + f'/{token}' body = f"Dear Sir/Madam,\n\nThis message is sent from Urban Buildings' Earthquake Resistance Assessor(UBERA).\nGo to the URL below to set up your account. The link has a validity of 1 hour.\nPlease access the link within that time.\n\nLink: {signup_url}\n\nBest Regards,\nUBERA Team" message= email.message.Message() message['Subject'] = 'UBERA Registration' message['From'] = sender message['To'] = receiver message.set_payload(body) # Create a secure SSL context context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: server.login(sender, password) server.sendmail(sender, receiver, message.as_string()) except CustomException as ce: print(str(ce)) raise CustomException(ce) except Exception as e: print(f"SignUp email not sent due to {str(e)}") raise CustomException("500:Mail not sent")
def monitor_alert(webpage, notes): ### AWS Config ### EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 # Setup email message message = email.message.Message() message['Subject'] = "Monitor Alert!" message['From'] = fromaddr message['To'] = ", ".join(toaddr) message.add_header('Content-Type', 'text/html') # HTML template = """\ <html> <head></head> <h2>Error Returned On:</h2> <body> <h3>%s</h3> <p><b>Notes:</b> <br> %s</p> </body> </html> """ % (webpage, notes) # Add html template as payload, and "stringify" content message.set_payload(template) msg_full = message.as_string() # Send message s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) s.starttls() s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) s.sendmail(fromaddr, toaddr, msg_full) s.quit()
def compat32_message(request): message = email.message.Message() message["To"] = email.header.Header("*****@*****.**") message["From"] = email.header.Header("*****@*****.**") message["Subject"] = "A message" message.set_payload("Hello World") return message
def _send_eng_message(subject, content): message = email.message.Message() message['Subject'] = subject message['From'] = _FROM_ADDR message['To'] = _SERVICE_RECIPIENT.encode('us-ascii') message['Content-Type'] = 'text/plain; charset=UTF-8' message.set_payload(content) _send(message)
def _makeMessage(self): from email.message import Message message = Message() message['From'] = 'Jim <*****@*****.**>' message['To'] = 'some-zope-coders:;' message['Date'] = 'Date: Mon, 19 May 2003 10:17:36 -0400' message['Message-Id'] = '<*****@*****.**>' message.set_payload('This is just an example\n') return message
def weekly_summary_email(summ_set, to_time, from_time): ### AWS Config ### EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 # Setup email message message = email.message.Message() message['Subject'] = 'Weekly Report: %s to %s \n\n' % (from_time, to_time) message['From'] = fromaddr message['To'] = ", ".join(toaddr) message.add_header('Content-Type', 'text/html') # HTML template = """\ <html> <head></head> <h1>Weekly Report:</h1> <body> """ for key in summ_set: summary_line = """\ <h3> %s </h3> <p> <b>Avg Response Time:</b> %s <br> <b>Max Response Time:</b> %s <br> <b>Total URLs:</b> %s <br> <b>Total Errors:</b> %s <br> <b>Avg TTFB:</b> %s <br> <b>Max TTFB:</b> %s <br> </p> """ % (key, summ_set[key][0], summ_set[key][1], summ_set[key][2], summ_set[key][3], summ_set[key][4], summ_set[key][5]) # Append single error string to list to join after loop template += summary_line template_end = """\ </body> </html> """ template = template + template_end # Add html template as payload, and "stringify" content message.set_payload(template) msg_full = message.as_string() # Send message s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) s.starttls() s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) s.sendmail(fromaddr, toaddr, msg_full) s.quit()
def _makeMessage(self): from email.message import Message message = Message() message["From"] = "Jim <*****@*****.**>" message["To"] = "some-zope-coders:;" message["Date"] = "Date: Mon, 19 May 2003 10:17:36 -0400" message["Message-Id"] = "<*****@*****.**>" message.set_payload("This is just an example\n") return message
def send(fromWho, to, subject, body, server): message = email.message.Message() message['To'] = to message['fromWho'] = fromWho message['Subject'] = subject message.set_payload(body) server = smtplib.SMTP(server) res = server.sendmail(fromWho, to, message.as_string()) server.quit() return res
def send(sender, to, subject="None", body="None", server="localhost"): message = email.message.Message() message["To"] = to message["From"] = sender message["Subject"] = subject message.set_payload(body) server = smtplib.SMTP(server) try: return server.sendmail(sender, to, message.as_string()) finally: server.quit()
def send_crawl_summary(domain, error_set): ### AWS Config ### EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 # Setup email message message = email.message.Message() message['Subject'] = "%s Crawl Summary Report" % domain message['From'] = fromaddr message['To'] = ", ".join(toaddr) message.add_header('Content-Type', 'text/html') # HTML template = """\ <html> <head></head> <h1>%s Report:</h1> <body> """ % domain for key in error_set: # Concatenates the 'key', (domain page), with the status code, [0], error text, [1], and response time, [2] err_line = """\ <p><h3>%s</h3> <br> <b>Status:</b> %s <br> <b>Response Time:</b> %s <br> <b>Error Message:</b> %s <br> </p> """ % (key, error_set[key][0], error_set[key][2], error_set[key][1]) # Append single error string to list to join after loop template = template + err_line # Join the string list and send it as the error body message template_end = """\ </body> </html> """ template = template + template_end # Add html template as payload, and "stringify" content message.set_payload(template) msg_full = message.as_string() # Send message s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) s.starttls() s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) s.sendmail(fromaddr, toaddr, msg_full) s.quit()
def do_POST(self): """ Echo a request with a body. """ message = self.get_message() try: length = int(self.headers["Content-Length"]) except (TypeError, ValueError) as exc: message.set_payload("Invalid Content-Length: {exc}".format(exc)) else: message.set_payload(self.rfile.read(length)) finally: self.send_head() BytesGenerator(self.wfile).flatten(message, unixfrom=False)
def send(sender, to, subject='None', body='None', server='localhost'): """sends a message.""" message = email.message.Message() message['To'] = to message['From'] = sender message['Subject'] = subject message.set_payload(body) server = smtplib.SMTP(server) try: return server.sendmail(sender, to, message.as_string()) finally: server.quit()
def send_mail(to_addrs, subject, body): if not isinstance(to_addrs, (tuple, list)): raise TypeError, 'send_mail() expects a tuple or list of recipients' if not to_addrs: return message = email.message.Message() message['From'] = admin_email for addr in to_addrs: message['To'] = addr message['Subject'] = subject message.set_payload(body) s = smtplib.SMTP(mail_host) s.sendmail(admin_email, to_addrs, message.as_string()) s.quit() return
def test_send_returns_messageId(self): from repoze.sendmail.delivery import DirectMailDelivery from email.message import Message mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) fromaddr = 'Jim <*****@*****.**' toaddrs = ('Guido <*****@*****.**>', 'Steve <steve@examplecom>') message = Message() message['From'] = 'Jim <*****@*****.**>' message['To'] = 'some-zope-coders:;' message['Date'] = 'Date: Mon, 19 May 2003 10:17:36 -0400' message['Subject'] = 'example' message.set_payload('This is just an example\n') msgid = delivery.send(fromaddr, toaddrs, message) self.assertTrue('.repoze.sendmail@' in msgid) self.assertEqual(message['Message-Id'], msgid)
def send( sender, to, subject='None', body='None', server='localhost' ): """sends a message.""" message = email.message.Message() message['To'] = to message['From'] = sender message['Subject'] = subject message.set_payload(body) server = smtplib.SMTP(server) try: return server.sendmail(sender, to, message.as_string()) finally: server.quit()
def test_send_returns_messageId(self): from repoze.sendmail.delivery import DirectMailDelivery from email.message import Message mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) fromaddr = "Jim <*****@*****.**" toaddrs = ("Guido <*****@*****.**>", "Steve <steve@examplecom>") message = Message() message["From"] = "Jim <*****@*****.**>" message["To"] = "some-zope-coders:;" message["Date"] = "Date: Mon, 19 May 2003 10:17:36 -0400" message["Subject"] = "example" message.set_payload("This is just an example\n") msgid = delivery.send(fromaddr, toaddrs, message) self.assertTrue(".repoze.sendmail@" in msgid) self.assertEqual(message["Message-Id"], msgid)
def _get_upload_content(field_storage): """Returns an email.Message holding the values of the file transfer. It decodes the content of the field storage and creates a new email.Message. Args: field_storage: cgi.FieldStorage that represents uploaded blob. Returns: An email.message.Message holding the upload information. """ message = email.message.Message() message.add_header( 'content-transfer-encoding', field_storage.headers.getheader('Content-Transfer-Encoding', '')) message.set_payload(field_storage.file.read()) payload = message.get_payload(decode=True) return email.message_from_string(payload)
def send_email(self, workspace, messages): '''Send an email according to the settings''' measurements = workspace.measurements assert isinstance(measurements, cpmeas.Measurements) message = email.message.Message() who_from = self.from_address.value who_to = [group.recipient.value for group in self.recipients] subject = measurements.apply_metadata(self.subject.value) message["Content-Type"] = "text/plain" message["From"] = who_from message["To"] = ",".join(who_to) message["Subject"] = subject payload = [] for msg in messages: msg = measurements.apply_metadata(msg) payload.append(msg) message.set_payload("\n".join(payload)) server_timeout = 30 if self.connection_security.value == C_NONE or self.connection_security.value == C_STARTTLS: server = smtplib.SMTP(host=self.smtp_server.value, port=self.port.value, timeout=server_timeout) if self.connection_security.value == C_STARTTLS: server.starttls() elif self.connection_security.value == C_SSL: server = smtplib.SMTP_SSL(host=self.smtp_server.value, port=self.port.value, timeout=server_timeout) try: if self.use_authentication.value: server.login(self.username.value, self.password.value) except Exception, instance: logger.error("Failed to send mail: %s", str(instance), exc_info=True) return "Failed to send mail: Authentication failed"
def test_send(self): from repoze.sendmail.delivery import DirectMailDelivery import transaction from email.message import Message mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) fromaddr = 'Jim <*****@*****.**' toaddrs = ('Guido <*****@*****.**>', 'Steve <steve@examplecom>') message = Message() message['From'] = 'Jim <*****@*****.**>' message['To'] = 'some-zope-coders:;' message['Date'] = 'Date: Mon, 19 May 2003 10:17:36 -0400' message['Message-Id'] = ext_msgid = '<*****@*****.**>' message['Subject'] = 'example' message.set_payload('This is just an example\n') msgid = delivery.send(fromaddr, toaddrs, message) self.assertEqual(msgid, '<*****@*****.**>') self.assertEqual(mailer.sent_messages, []) transaction.commit() self.assertEqual(mailer.sent_messages, [(fromaddr, toaddrs, message)]) mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) self.assertTrue('@' in msgid) self.assertEqual(mailer.sent_messages, []) transaction.commit() self.assertEqual(len(mailer.sent_messages), 1) self.assertEqual(mailer.sent_messages[0][0], fromaddr) self.assertEqual(mailer.sent_messages[0][1], toaddrs) self.assertEqual(mailer.sent_messages[0][2].get_payload(), 'This is just an example\n') self.assertEqual(message['Message-Id'], msgid) self.assertEqual(message['Message-Id'], ext_msgid) mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) self.assertEqual(mailer.sent_messages, []) transaction.abort() self.assertEqual(mailer.sent_messages, [])
def create_checkpoint(self): policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) message['Version'] = str(self.VERSION) message['Content-Type'] = 'application/json; charset=utf-8' checkpoint = json.dumps( self.serialize(), ensure_ascii=False, indent=' ', sort_keys=True, cls=JSONEncoder) serialized_checkpoint = checkpoint.encode('utf-8') message.set_payload(serialized_checkpoint) checkpoint_data = message.as_bytes() self.storage.add_checkpoint(checkpoint_data)
def serialize_command(self, cmd, target_id, now): serialized = json.dumps( cmd.serialize(), ensure_ascii=False, indent=' ', sort_keys=True, cls=JSONEncoder) policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) message['Version'] = str(self.VERSION) message['Content-Type'] = 'application/json; charset=utf-8' message['Target'] = target_id message['Time'] = time.ctime(now) message['Timestamp'] = '%d' % now message.set_payload(serialized.encode('utf-8')) return message.as_bytes()
def read_email(folder, output): with (folder / 'InternetHeaders.txt').open('rb') as f: raw_headers = f.read() message = email.message_from_bytes(raw_headers) del message['Content-Type'] message.set_payload(None) message['Content-Type'] = 'multipart/mixed' html_file = folder / 'Message.html' text_file = folder / 'Message.txt' if html_file.exists(): with html_file.open('rb') as f: html_src = f.read() utf8 = bool(re.search(br'charset\s*=["\']?utf[-]?8', html_src[:1024])) params = {'charset': 'utf-8'} if utf8 else {} html = MIMEBase('text', 'html', **params) html.set_payload(html_src) email.encoders.encode_base64(html) message.attach(html) elif text_file.exists(): text = MIMEBase('text', 'plain') with text_file.open('rb') as f: text.set_payload(f.read()) email.encoders.encode_base64(text) message.attach(text) attachments_dir = folder / 'Attachments' if attachments_dir.exists(): for p in attachments_dir.iterdir(): if p.is_dir(): for i in p.iterdir(): if i.name.startswith('Message'): message.attach(get_message_attachment(i)) else: raise RuntimeError('unknown attachment {!r}'.format(i)) else: message.attach(get_file_attachment(p)) output.write(message.as_bytes())
def test_send(self): from repoze.sendmail.delivery import DirectMailDelivery import transaction from email.message import Message mailer = _makeMailerStub() delivery = DirectMailDelivery(mailer) fromaddr = "Jim <*****@*****.**" toaddrs = ("Guido <*****@*****.**>", "Steve <steve@examplecom>") message = Message() message["From"] = "Jim <*****@*****.**>" message["To"] = "some-zope-coders:;" message["Date"] = "Date: Mon, 19 May 2003 10:17:36 -0400" message["Message-Id"] = ext_msgid = "<*****@*****.**>" message["Subject"] = "example" message.set_payload("This is just an example\n") msgid = delivery.send(fromaddr, toaddrs, message) self.assertEqual(msgid, "<*****@*****.**>") self.assertEqual(mailer.sent_messages, []) transaction.commit() self.assertEqual(mailer.sent_messages, [(fromaddr, toaddrs, message)]) mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) self.assertTrue("@" in msgid) self.assertEqual(mailer.sent_messages, []) transaction.commit() self.assertEqual(len(mailer.sent_messages), 1) self.assertEqual(mailer.sent_messages[0][0], fromaddr) self.assertEqual(mailer.sent_messages[0][1], toaddrs) self.assertEqual(mailer.sent_messages[0][2].get_payload(), "This is just an example\n") self.assertEqual(message["Message-Id"], msgid) self.assertEqual(message["Message-Id"], ext_msgid) mailer.sent_messages = [] msgid = delivery.send(fromaddr, toaddrs, message) self.assertEqual(mailer.sent_messages, []) transaction.abort() self.assertEqual(mailer.sent_messages, [])
def _send_message(test_id, part_number, username, password, sender, recipient, headers, subject, body, cls=smtplib.SMTP): if settings.SMTP_SERVER_SSL and cls is smtplib.SMTP: # Only set the SSL class if the default is not already overridden cls = smtplib.SMTP_SSL conn = cls(settings.SMTP_SERVER_HOST, settings.SMTP_SERVER_PORT) conn.ehlo_or_helo_if_needed() if settings.SMTP_SERVER_STARTTLS: conn.starttls() conn.ehlo_or_helo_if_needed() if settings.SMTP_SERVER_HOST not in ('127.0.0.1', 'localhost', '::1'): try: conn.login(username, password) except smtplib.SMTPResponseException: CURRENT_TESTS[test_id]['error'] = \ 'Could not authenticate to send message' message = email.message.Message() message.set_charset('UTF8') for header_key, header_value in headers: encoded_header_value = str(email.header.Header(header_value, 'UTF8')) message.add_header(header_key, encoded_header_value) encoded_subject = str(email.header.Header(subject, 'UTF8')) encoded_sender = str(email.header.Header(sender, 'UTF8')) encoded_recipient = str(email.header.Header(recipient, 'UTF8')) message.add_header('Subject', encoded_subject) message.add_header('From', encoded_sender) message.add_header('To', encoded_recipient) message.set_type('text/plain') message.set_param('charset', 'UTF8') message.set_payload(body, 'UTF8') refused = conn.sendmail(sender, [recipient], message.as_string()) if refused: CURRENT_TESTS[test_id]['error'] = 'Recipient refused.' conn.quit()
def test_from_emailmessage(self): message = EmailMessage() body = 'message that is not urgent' try: message.set_content(body) except AttributeError: # Python2 message.set_payload(body) message.set_default_type('text/plain') message['Subject'] = 'URGENT TITLE' message['From'] = '*****@*****.**' message['To'] = '*****@*****.**' mail = Mail.from_EmailMessage(message) self.assertEqual(mail.subject.get(), 'URGENT TITLE') self.assertEqual(mail.from_email.email, '*****@*****.**') self.assertEqual(len(mail.personalizations), 1) self.assertEqual(len(mail.personalizations[0].tos), 1) self.assertEqual(mail.personalizations[0].tos[0], {'email': '*****@*****.**'}) self.assertEqual(len(mail.contents), 1) content = mail.contents[0] self.assertEqual(content.type, 'text/plain') self.assertEqual(content.value, 'message that is not urgent')
def sendMessage(fromByValue, toByValue, subject, body, headerByName=None): 'Send a message using SMTP' # Prepare message = email.message.Message() message.add_header('from', email.utils.formataddr((fromByValue['nickname'], fromByValue['email']))) message.add_header('to', email.utils.formataddr((toByValue['nickname'], toByValue['email']))) message.add_header('subject', subject) message.set_payload(body) if headerByName: for key, value in headerByName.iteritems(): message.add_header(key, value) # Connect to server if fromByValue['smtp'] == 'localhost': server = smtplib.SMTP('localhost') else: server = smtplib.SMTP_SSL(fromByValue['smtp'], 465) if len(fromByValue['username']): server.login(fromByValue['username'], fromByValue['password']) # Send mail try: server.sendmail(fromByValue['email'], toByValue['email'], message.as_string()) except socket.error, error: raise SMTPError(error)
def send_pass_reset_email(receiver, token): try: port = 465 # For SSL sender, password = EMAIL, PASSWORD pass_reset_url = PASS_RESET_URL + f'/{token}' body = f"Dear Sir/Madam,\n\nThis message is sent from Urban Buildings' Earthquake Resistance Assessor(UBERA).\nGo to the URL below to reset your password. The link has a validity of 1 hour.\nPlease access the link within that time.\n\nLink: {pass_reset_url}\n\nBest Regards,\nUBERA Team" message= email.message.Message() message['Subject'] = 'UBERA Password Reset' message['From'] = sender message['To'] = receiver message.set_payload(body) # Create a secure SSL context context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: server.login(sender, password) server.sendmail(sender, receiver, message.as_string()) except Exception: # log raise CustomException("500:Mail not sent")
def construct_gmail_message(payload): message = email.message.Message() for header in payload['headers']: message[header['name']] = header['value'] if message.get_content_maintype() == 'multipart': message.set_payload( [construct_gmail_message(part) for part in payload['parts']]) else: cte = message.get('Content-Transfer-Encoding') if cte is not None: del message['Content-Transfer-Encoding'] message['X-Original-Content-Transfer-Encoding'] = cte try: external_id = payload['body']['attachmentId'] ct = message.get_content_type() message.replace_header('Content-Type', 'text/plain') message.set_payload( 'Attachment with type %s, ID %r omitted; retrieve separately' % (ct, external_id)) except KeyError: body = payload['body']['data'] body += '=' * (4 - len(body) % 4) message.set_payload(base64.urlsafe_b64decode(body)) return message
import email.message import mailbox mail = mailbox.mbox("empty.mbox") mail.close() mail = mailbox.mbox("one-message.mbox") message = email.message.Message() message.set_payload("a") message.add_header("h", "v", k="l") mail.add(message) mail.close()
# Define charset and set content-transfer-encoding to # quoted-printable charset = email.charset.Charset('utf-8') charset.header_encoding = email.charset.QP charset.body_encoding = email.charset.QP # Create message-object, fill it and set correct charset. message = email.message.Message() header = email.header.Header(subject, charset) message['To'] = toaddr message['From'] = fromaddr message['Subject'] = header message.set_charset(charset) message.set_payload(msg) # send mail program.communicate(message.as_string()) def get_host_name(ip): """Get hostname based on ip-address. Return 'N/A' if not found.""" hostname = "N/A" try: hostname = socket.gethostbyaddr(ip)[0] except socket.herror: pass return hostname
def create_plain_message(body_bytes): message = email.message.Message() message.set_payload(body_bytes) return message
def craft_message(headers, body, attachments, embeddeds, mbx, is_html): """This function handles the creation of a Python email.message object from the headers and body lists created during the main loop.""" global edir attachments_ok = False embeddedcids = [] if body: msg_text = ''.join(body) else: msg_text = '' # there's no point honoring 'multipart' if we don't have any # attachments or embeddeds to attach, so we'll pay most # attention to whether we have any attachments or embeddeds # defined for this message if attachments or embeddeds: is_multipart = True else: is_multipart = False message = None contenttype = headers.getValue('Content-Type:') if contenttype and re_html.search(contenttype): is_html = True if not contenttype: msattach = headers.getValue('X-MS-Attachment:') if msattach: message = MIMEMultipart() attachments_ok = "Dunno" attachments_contenttype = "Still Dunno" else: if is_html: message = MIMENonMultipart('text', 'html') else: message = MIMENonMultipart('text', 'plain') attachments_ok = False attachments_contenttype = False print "T", elif re_rfc822.search(contenttype): print "[", message = MIMEMessage( craft_message(*extract_pieces(body, -1, mbx, True))) print "]", elif not is_multipart: mimetype = re_single_contenttype.search(contenttype) if mimetype: main = mimetype.group(1) sub = mimetype.group(2) if main != 'multipart': message = MIMENonMultipart(main, sub) attachments_ok = False attachments_contenttype = False print "X", else: # I've seen some messages in Eudora # mailboxes that label themselves as # multitype/related without having any # attachments ever declared in the # Eudora box. # # By passing here, we allow the next # clause to go ahead and create an # appropriate MIMENonMultipart pass if not message: if is_html: message = MIMENonMultipart('text', 'html') else: message = MIMENonMultipart('text', 'plain') attachments_ok = False attachments_contenttype = False else: subtype = re_multi_contenttype.search(contenttype) if subtype: message = MIMEMultipart(_subtype=subtype.group(1)) attachments_ok = subtype.group(1) attachments_contenttype = contenttype print "Y", else: message = MIMEMultipart() print "Z", attachments_ok = "Dunno" attachments_contenttype = "Still Dunno" # Need to add support here for processing embeddeds if embeddeds: if not isinstance(message, MIMEMultipart): print "\n\n==================================================\n" print "Found surprise multipart for embeddeds!\n" message = MIMEMultipart(_subtype='related') else: print "\n\n==================================================\n" print "Found embeddeds in multipart!\n" p = EudoraHTMLParser() try: p.feed(msg_text) cids = p.get_cids() except HTMLParseError: # okay, we've got unparseable HTML here. # Let's just use a quick regexp to see if we can make sense of this. cids = [] for match in re_cids_finder.finditer(msg_text): cids.append("cid:" + match.group(1)) if not len(cids) == len(embeddeds): print "cids / embeddeds mismatch!" print print mbx for piece in ['To:', 'From:', 'Subject:', 'Date:']: if headers.getValue(piece): print piece + " " + headers.getValue(piece)[:80] print print "\tcid\t\t\t\t\t\t\tembedded" i = 0 while i < len(cids) or i < len(embeddeds): if i < len(cids): print "%d.\t%s" % (i, cids[i]), print "\t" * (6 - (len(cids[i]) // 8)), else: print "%d.\t" % (i, ), print "\t\t\t\t\t\t", if i < len(embeddeds): print embeddeds[i], if edir and os.path.exists(edir + os.sep + embeddeds[i]): print " *" else: print " !" else: print i = i + 1 cidi = 0 embeddedi = 0 cidsmatched = set() while cidi < len(cids) or embeddedi < len(embeddeds): if cidi < len(cids) and embeddedi < len(embeddeds): if cids[cidi].startswith('cid:'): actualcid = cids[cidi][4:] else: actualcid = cids[cidi] # the document might have several img # references to the same cid.. we # don't want to try to mate up # multiple inline files in that case if actualcid in cidsmatched: cidi = cidi + 1 else: cidsmatched.add(actualcid) embeddedcids.append((actualcid, embeddeds[embeddedi])) embeddedi = embeddedi + 1 cidi = cidi + 1 elif embeddedi < len(embeddeds): embeddedcids.append((None, embeddeds[embeddedi])) embeddedi = embeddedi + 1 else: # we have more cids than # embeddeds, keep looping # through cidi = cidi + 1 print "\n\nAttaching inline components:" for c, f in embeddedcids: print "%s\t%s" % (c, f) print "\n==================================================\n" if attachments: if not isinstance(message, MIMEMultipart): #print "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" #print "Forcing surprise multipart!\n" #print "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" message = MIMEMultipart() # bind the headers into our message set_headers(message, headers) try: # rfc822 MIMEMessage objects handle payload management # on constructions, we must not try to do it here. if not isinstance(message, MIMEMessage): if not isinstance(message, MIMEMultipart): message.set_payload(msg_text) elif is_html: message.attach(MIMEText(msg_text, _subtype='html')) else: message.attach(MIMEText(msg_text)) except Exception, e: print "\nHEY HEY HEY message = " + str(msg_text) + "\n" print "Type of message's payload is " + str(type( message.get_payload())) + "\n" if isinstance(message.get_payload(), list): print "Size of message's payload list is " + str( len(message.get_payload())) + "\n" print ")))))))))))))))))))) First part" print str(message.get_payload()[0]) print ">>>>>>>>>>>>>>>>>>>> Second part" print str(message.get_payload()[1]) print "attachments_contenttype is (%s)" % (attachments_contenttype, ) print "attachments_ok is (%s)" % (attachments_ok, ) if attachments: print "Yeah, attachments were found: %d" % (len(attachments), ) print "EXCEPTION " + str(e) + "\n" traceback.print_exc(file=sys.stdout)
def craft_message( headers, body, attachments, embeddeds, mbx, is_html): """This function handles the creation of a Python email.message object from the headers and body lists created during the main loop.""" global edir attachments_ok = False embeddedcids = [] if body: msg_text = ''.join(body) else: msg_text = '' # there's no point honoring 'multipart' if we don't have any # attachments or embeddeds to attach, so we'll pay most # attention to whether we have any attachments or embeddeds # defined for this message if attachments or embeddeds: is_multipart = True else: is_multipart = False message = None contenttype = headers.getValue('Content-Type:') if contenttype and re_html.search(contenttype): is_html = True if not contenttype: msattach = headers.getValue('X-MS-Attachment:') if msattach: message = MIMEMultipart() attachments_ok = "Dunno" attachments_contenttype = "Still Dunno" else: if is_html: message = MIMENonMultipart('text', 'html') else: message = MIMENonMultipart('text', 'plain') attachments_ok = False attachments_contenttype = False print "T", elif re_rfc822.search( contenttype ): print "[", message = MIMEMessage(craft_message(*extract_pieces(body, -1, mbx, True))) print "]", elif not is_multipart: mimetype = re_single_contenttype.search( contenttype ) if mimetype: main = mimetype.group(1) sub = mimetype.group(2) if main != 'multipart': message = MIMENonMultipart(main, sub) attachments_ok = False attachments_contenttype = False print "X", else: # I've seen some messages in Eudora # mailboxes that label themselves as # multitype/related without having any # attachments ever declared in the # Eudora box. # # By passing here, we allow the next # clause to go ahead and create an # appropriate MIMENonMultipart pass if not message: if is_html: message = MIMENonMultipart('text', 'html') else: message = MIMENonMultipart('text', 'plain') attachments_ok = False attachments_contenttype = False else: subtype = re_multi_contenttype.search( contenttype ) if subtype: message = MIMEMultipart(_subtype=subtype.group(1)) attachments_ok = subtype.group(1) attachments_contenttype = contenttype print "Y", else: message = MIMEMultipart() print "Z", attachments_ok = "Dunno" attachments_contenttype = "Still Dunno" # Need to add support here for processing embeddeds if embeddeds: if not isinstance( message, MIMEMultipart): print "\n\n==================================================\n" print "Found surprise multipart for embeddeds!\n" message = MIMEMultipart(_subtype='related') else: print "\n\n==================================================\n" print "Found embeddeds in multipart!\n" p = EudoraHTMLParser() try: p.feed(msg_text) cids = p.get_cids() except HTMLParseError: # okay, we've got unparseable HTML here. # Let's just use a quick regexp to see if we can make sense of this. cids = [] for match in re_cids_finder.finditer(msg_text): cids.append("cid:" + match.group(1)) if not len(cids) == len(embeddeds): print "cids / embeddeds mismatch!" print print mbx for piece in ['To:', 'From:' , 'Subject:', 'Date:']: if headers.getValue(piece): print piece + " " + headers.getValue(piece)[:80] print print "\tcid\t\t\t\t\t\t\tembedded" i = 0 while i < len(cids) or i < len(embeddeds): if i < len(cids): print "%d.\t%s" % (i, cids[i]), print "\t" * (6 - (len(cids[i]) // 8)), else: print "%d.\t" % (i, ), print "\t\t\t\t\t\t", if i < len(embeddeds): print embeddeds[i], if edir and os.path.exists(edir + os.sep + embeddeds[i]): print " *" else: print " !" else: print i = i + 1 cidi = 0 embeddedi = 0 cidsmatched = set() while cidi < len(cids) or embeddedi < len(embeddeds): if cidi < len(cids) and embeddedi < len(embeddeds): if cids[cidi].startswith('cid:'): actualcid = cids[cidi][4:] else: actualcid = cids[cidi] # the document might have several img # references to the same cid.. we # don't want to try to mate up # multiple inline files in that case if actualcid in cidsmatched: cidi = cidi + 1 else: cidsmatched.add(actualcid) embeddedcids.append( (actualcid, embeddeds[embeddedi]) ) embeddedi = embeddedi + 1 cidi = cidi + 1 elif embeddedi < len(embeddeds): embeddedcids.append( (None, embeddeds[embeddedi]) ) embeddedi = embeddedi + 1 else: # we have more cids than # embeddeds, keep looping # through cidi = cidi + 1 print "\n\nAttaching inline components:" for c, f in embeddedcids: print "%s\t%s" % (c, f) print "\n==================================================\n" if attachments: if not isinstance( message, MIMEMultipart): #print "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" #print "Forcing surprise multipart!\n" #print "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" message = MIMEMultipart() # bind the headers into our message set_headers( message, headers ) try: # rfc822 MIMEMessage objects handle payload management # on constructions, we must not try to do it here. if not isinstance( message, MIMEMessage ): if not isinstance( message, MIMEMultipart): message.set_payload(msg_text) elif is_html: message.attach(MIMEText(msg_text, _subtype='html')) else: message.attach(MIMEText(msg_text)) except Exception, e: print "\nHEY HEY HEY message = " + str(msg_text) + "\n" print "Type of message's payload is " + str(type(message.get_payload())) + "\n" if isinstance( message.get_payload(), list ): print "Size of message's payload list is " + str(len(message.get_payload())) + "\n" print ")))))))))))))))))))) First part" print str(message.get_payload()[0]) print ">>>>>>>>>>>>>>>>>>>> Second part" print str(message.get_payload()[1]) print "attachments_contenttype is (%s)" % (attachments_contenttype, ) print "attachments_ok is (%s)" % (attachments_ok, ) if attachments: print "Yeah, attachments were found: %d" % (len(attachments), ) print "EXCEPTION " + str(e) + "\n" traceback.print_exc(file=sys.stdout)