3

I wrote a script for backing up my Neo4J DB.

At the end of the backup process and email is sent to the DB Administrator

The email received without the message_body.

This is the code:

message = MIMEMultipart('alternative')
message['To'] = "Database Admin <%s>" % _receiver
message['From'] = "Pico.buzz Graph Database <%s>" % _sender
if not log.is_error():
    message['Subject'] = "Graph DB Backup Finished Successfully"
    message_body = 'Successfully backup email. Please see review log file'
else:
    message['Subject'] = "ATTENTION: ERROR! Graph DB Backup Failed"
    message_body = 'An error occur during backup. please review log'
instance_name = aws.get_instance_name()
instance_details = "Instance Id: %s\nPrivate IP Address: %s" % (aws.get_instance_id(), aws.get_instance_ip())
if instance_name is not None:
    instance_details = """Instance Name: %s\n%s""" % (instance_name, instance_details)
message_body = "%s\n\n%s" % (message_body, instance_details)
content = MIMEText(message_body, 'plain')
message.attach(content)
message.attach(_get_log_file())
smtp = smtplib.SMTP('localhost')
smtp.sendmail(_sender, _receiver, message.as_string())
log.info(__name__, "Successfully sent email to: %s" % _receiver)

Any idea why?

erip
  • 16,374
  • 11
  • 66
  • 121
Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • You've confirmed that `message_body` is what you expect before your `sendmail` call I presume? – erip Jan 10 '16 at 15:29
  • I printed it and was happy.. :) – Asaf Nevo Jan 10 '16 at 15:30
  • Unrelated, but `%s` formatting is typically avoided. You should look at [this](https://docs.python.org/3/library/functions.html#format). – erip Jan 10 '16 at 15:33
  • Try changing the first line to `message = MIMEMultipart('mixed')`. – erip Jan 10 '16 at 15:40
  • 1
    Which version of python do you use? What `type(_get_log_file())` returns? What happens, if you first attach `_get_log_file()` to the message, and the `content` (order of attachment matters)? – vrs Jan 10 '16 at 15:41
  • @erip `message = MIMEMultipart('mixed')` actually worked.. post it as an answer and i'll accept it – Asaf Nevo Jan 13 '16 at 11:13

1 Answers1

0

MIMEMultipart takes as a parameter to the constructor a multipart subtype.

You were using the subtype 'alternative'. The alternative subtype allows the email to be sent with HTML and text.

You wanted to submit an email with text and an attachment, so you need to construct MIMEMultipart with the subtype 'mixed'.

For more details about these subtypes, you can look at the MIME Wikipedia entry on Multipart messages.

erip
  • 16,374
  • 11
  • 66
  • 121