2 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Chromite email utility functions."""
9 from email.mime.application import MIMEApplication
10 from email.mime.multipart import MIMEMultipart
11 from email.mime.text import MIMEText
18 # Note: When importing this module from cbuildbot code that will run on
19 # a builder in the golo, set this to constants.GOLO_SMTP_SERVER
20 DEFAULT_SMTP_SERVER = 'localhost'
23 def SendEmail(subject, recipients, smtp_server=None, message='',
24 attachment=None, extra_fields=None):
25 """Send an e-mail job notification with the given message in the body.
28 subject: E-mail subject.
29 recipients: list of e-mail recipients.
30 smtp_server: (optional) Hostname[:port] of smtp server to use to send
31 email. Defaults to DEFAULT_SMTP_SERVER.
32 message: (optional) Message to put in the e-mail body.
33 attachment: (optional) text to attach.
34 extra_fields: (optional) A dictionary of additional message header fields
35 to be added to the message. Custom fields names should begin
38 # Ignore if the list of recipients is empty.
42 extra_fields = extra_fields or {}
45 smtp_server = DEFAULT_SMTP_SERVER
47 sender = socket.getfqdn()
48 email_recipients = recipients
50 for key, val in extra_fields.iteritems():
53 msg['Subject'] = subject
54 msg['To'] = ', '.join(recipients)
56 msg.attach(MIMEText(message))
58 s = cStringIO.StringIO()
59 with gzip.GzipFile(fileobj=s, mode='w') as f:
61 part = MIMEApplication(s.getvalue(), _subtype='x-gzip')
63 part.add_header('Content-Disposition', 'attachment', filename='logs.txt.gz')
66 smtp_client = smtplib.SMTP(smtp_server)
67 smtp_client.sendmail(sender, email_recipients, msg.as_string())
71 def SendEmailLog(subject, recipients, smtp_server=None, message='',
72 inc_trace=True, log=None, extra_fields=None):
73 """Send an e-mail with a stack trace and log snippets.
76 subject: E-mail subject.
77 recipients: list of e-mail recipients.
78 smtp_server: (optional) Hostname(:port) of smtp server to use to send
79 email. Defaults to DEFAULT_SMTP_SERVER.
80 message: Message to put at the top of the e-mail body.
81 inc_trace: Append a backtrace of the current stack.
82 log: List of lines (log data) to include in the notice.
83 extra_fields: (optional) A dictionary of additional message header fields
84 to be added to the message. Custom fields names should begin
92 if sys.exc_info() != (None, None, None):
93 trace = traceback.format_exc()
94 message += '\n\n' + trace
99 '***************************\n' +
100 'Last log messages:\n' +
101 '***************************\n' +
103 attachment = ''.join(log)
105 SendEmail(subject, recipients, smtp_server, message=message,
106 attachment=attachment, extra_fields=extra_fields)