def send(self, recipient_list, subject='Sem assunto', attachment_list='False'): emailRegex = re.compile( r'''([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))''', re.VERBOSE) valid_recipients = [] invalid_recipients = [] for i in recipient_list: email = emailRegex.findall(i) if email: valid_recipients.append(email) else: invalid_recipients.append(email) try: with Outbox(username=smtp_user, password=smtp_pass, server=smtp_server, port=smtp_port, mode='SSL') as outbox: if attachment_list == 'False': attachments = [] for i in attachment_list: attachments.append( Attachment(str(i), fileobj=open(i, 'rb'))) outbox.send(Email( subject=subject, html_body='<b>SOME REALLY NICE SENTIMENT</b>', recipients=valid_recipients), attachments=attachments) response = self.get_mail_sent_ok_message() if len(invalid_recipients) > 0: response = response + '\n' + self.get_invalid_mails_filtered_by_regex( ) for invalid in invalid_recipients: response = response + '\n' + invalid return response else: outbox.send( Email(subject=subject, html_body='<b>SOME REALLY NICE SENTIMENT</b>', recipients=valid_recipients)) response = self.get_mail_sent_ok_message() if len(invalid_recipients) > 0: response = response + '\n' + self.get_invalid_mails_filtered_by_regex( ) for invalid in invalid_recipients: response = response + '\n' + invalid return response finally: pass
def send(self, msg, from_=None): headers = msg.headers or {} atts = [ Attachment(att['name'], StringIO(att['contents'])) for att in msg.attachments ] if msg.attachments else [] if 'From' not in msg.headers: headers['From'] = msg.from_ if msg.cc and 'CC' not in headers: headers['CC'] = ', '.join( msg.cc) if not isinstance(msg.cc, basestring) else msg.cc if msg.bcc and 'BCC' not in headers: headers['BCC'] = ', '.join( msg.bcc) if not isinstance(msg.bcc, basestring) else msg.bcc body, html_body = (None, msg.body) if msg.is_html else (msg.body, None) email = Email(msg.to, msg.subject, body, html_body, msg.charset, headers, msg.is_rfc2231) try: with self.conn_class(*self.conn_args) as conn: conn.send(email, atts, from_ or msg.from_) except Exception, e: logger.warn('Could not send an SMTP message to `%s`, e:`%s`', self.config_no_sensitive, format_exc(e))
def test_content_type(): alt = 'multipart/alternative' mixed = 'multipart/mixed' text = 'text/plain' html = 'text/html' octstr = 'application/octet-stream' attachments = [Attachment('filename', fileobj=StringIO('content'))] def t(m, root_ct, root_cs, expected_parts): def cmpcs(actual, expected): if expected is None: assert actual is None else: assert lookup(actual.input_charset) == lookup(expected) assert m.get_content_type() == root_ct cmpcs(m.get_charset(), root_cs) p = m.get_payload() for p, e in zip(m.get_payload(), expected_parts): typ, ct, cs = e assert isinstance(p, typ) assert p.get_content_type() == ct cmpcs(p.get_charset(), cs) e = Email(recipients=['*****@*****.**'], subject='subject', body='body') t(e.as_mime(), text, 'utf8', []) t(e.as_mime(attachments), mixed, None, [(MIMEText, text, 'utf8'), (MIMEBase, octstr, None)]) e = Email(recipients=['*****@*****.**'], subject='subject', html_body='body') t(e.as_mime(), html, 'utf8', []) t(e.as_mime(attachments), mixed, None, [(MIMEText, html, 'utf8'), (MIMEBase, octstr, None)]) e = Email(recipients=['*****@*****.**'], subject='subject', body='body', html_body='body') t(e.as_mime(), alt, None, [(MIMEText, text, 'utf8'), (MIMEText, html, 'utf8')]) t(e.as_mime(attachments), mixed, None, [(MIMEBase, alt, None), (MIMEBase, octstr, None)]) t(e.as_mime(attachments).get_payload()[0], alt, None, [(MIMEText, text, 'utf8'), (MIMEText, html, 'utf8')])
def _send_email(config_file, subject, body): with open(config_file, 'r') as f: config = json.load(f) port = config["port"] server = config["server"] fromaddr = config["fromaddr"] toaddrs = config["toaddrs"] username = config["username"] password = config["password"] outbox = Outbox(username=username, password=password, server=server, port=port) email = Email(subject=subject, body=body, recipients=toaddrs) outbox.send(email)
def test_rfc2231(): filename = u'ファイル名' a = [Attachment(filename, fileobj=StringIO('this is some data'))] e = Email(['*****@*****.**'], 'subject', 'body') assert e.as_mime(a).get_payload()[1].get_filename() == filename e = Email(['*****@*****.**'], 'subject', 'body', rfc2231=True) assert e.as_mime(a).get_payload()[1].get_filename() == filename e = Email(['*****@*****.**'], 'subject', 'body', rfc2231=False) h, enc = decode_header(e.as_mime(a).get_payload()[1].get_filename())[0] assert h.decode(enc) == filename
def send(self, msg, from_=None): headers = msg.headers or {} atts = [] if msg.attachments: for item in msg.attachments: contents = item['contents'] contents = contents.encode('utf8') if isinstance( contents, unicode) else contents att = Attachment(item['name'], BytesIO(contents)) atts.append(att) if 'From' not in msg.headers: headers['From'] = msg.from_ if msg.cc and 'CC' not in headers: headers['CC'] = ', '.join( msg.cc) if not isinstance(msg.cc, basestring) else msg.cc if msg.bcc and 'BCC' not in headers: headers['BCC'] = ', '.join( msg.bcc) if not isinstance(msg.bcc, basestring) else msg.bcc body, html_body = (None, msg.body) if msg.is_html else (msg.body, None) email = Email(msg.to, msg.subject, body, html_body, msg.charset, headers, msg.is_rfc2231) try: with self.conn_class(*self.conn_args) as conn: conn.send(email, atts, from_ or msg.from_) except Exception: logger.warn('Could not send an SMTP message to `%s`, e:`%s`', self.config_no_sensitive, format_exc()) else: if logger.isEnabledFor(INFO): atts_info = ', '.join(att.name for att in atts) if atts else None logger.info( 'SMTP message `%r` sent from `%r` to `%r`, attachments:`%r`', msg.subject, msg.from_, msg.to, atts_info)
def send(account: Account, to: str, subject: str, body: str, attachment, attachment_name): if not body: raise EmptyBody with Outbox(server=account.smtp_host, port=account.smtp_port, username=account.address, password=account.password, mode='SSL' if account.smtp_ssl else None) as connection: email = Email(recipients=to, subject=subject, body=body) attachments = [] if attachment: attachments.append(Attachment(attachment_name, attachment)) try: connection.send(email, attachments) except SMTPRecipientsRefused: raise IncorrectAddress
def send_report(report): message = '' for server_key, server_report in report.items(): message += "SERVER %s: \n\n" % server_key if isinstance(server_report, dict): remote_report = server_report.get("remote") del (server_report["remote"]) for db_name, db_report in server_report.items(): message += "\tDB %s: %s\n" % (db_name, db_report) if remote_report: message += "\n\t[Remote server (scp)]: %s\n" % remote_report else: message += "%s" % server_report message += "\n\n" print(message) try: import socket from outbox import Outbox, Email, Attachment hostname = socket.gethostname() smtp = namedtuple('smtp', settings.smtp.keys())(**settings.smtp) attachments = [ Attachment('backup.log', fileobj=open(settings.logfile)) ] outbox = Outbox(username=smtp.user, password=smtp.password, server=smtp.host, port=smtp.port, mode='SSL') message = "HOST: %s\n\n" % hostname + message outbox.send(Email(subject='[%s] Daily backup report' % hostname, body=message, recipients=settings.emails), attachments=attachments) # if report sent, we can remove log file os.unlink(settings.logfile) except Exception as e: logger.error("Can't send report via email") logger.exception(e)
def test_encoding(): for body in [u'すすめ商品を見るに', u'Российская Федерация']: message = Email(['*****@*****.**'], 'subject', body) text = message.as_mime().as_string() assert base64.b64encode(body.encode('UTF-8')).decode('utf8') in text, u"The encoded form of '%s' is incorrect!" % body
def send(self, subject, message, recipients): self.outbox.send(Email(subject=subject, html_body=message, recipients=recipients))