HTML and Plaintext email over Python through Zabbix - python

I'm working on a script that creates both an HTML and Plaintext email. This didn't seem like a hassle, but I can't hardcode the e-mail into the script I'm using. Allow me to explain why.
I'm using the Zabbix Monitoring system to keep an eye out for my systems. Allow me to use a printer for example. Once one of the toners is close to dying, I want both an HTML and plain text mail to be sent. Zabbix uses several macros however, which can be used to identify what system is being affected by what.
So, the HTML body needs to received before the script is run. Once the HTML body has been received with the correct values, it needs to have a plain copy too. As much as I'd like to have the plain-text contain the correct parameters (copied from the macros) too, I don't consider this a necessity.
This is what my script currently looks like.
#!/usr/bin/env python
list1=[0, 1, 2, 3, 4];
import mimetypes, os, smtplib, sys
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "x"
you = "y"
DESTINATION=sys.argv[1]
SUBJECT=sys.argv[2]
MESSAGE=sys.argv[3]
PASS='password'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
text = "A problem has been detected on {HOST.NAME} \n \n Trigger: {TRIGGER.NAME} \n Status: {TRIGGER.STATUS} \n Severity: {TRIGGER.SEVERITY} "
#html =
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
#part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
#msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('mysmtpserver')
s.ehlo()
s.starttls()
s.ehlo()
s.login(me, PASS)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
The reason why I can't have them being sent seperately or sending the HTML copy alone is because my e-mails get nuked by SpamAssassin. I'm intending to send certain error messages to my customers. So they are immediately notified when their toner is nearly empty, so they can place a new order. The HTML-email has been set up and has been working without failure.
So to put it onto perspective one more time.
Zabbix recieves an error.
There is a default HTML message written, macros become filled, this then needs to be imported to the script.
The script is then run.
There's an e-mail sent with both HTML content as well as the
plain-text for users that can't read the HTML-emails.
The reason the script is a mess is because I've already tried several options, but I can't seem to figure this one out.

Related

I am using the SMTPLib to send an email to gmail account

I have two messages.One is the HTML Message and the other one is a simple plain text message.I am attaching both of them to the MIMEMultipart variable(tmessage) but when the email get send, i can only see the second attached message in my inbox. I cannot figure out why...Here is my code
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
host='smtp.gmail.com'
port=587
message="<h1>Hey i have received a 3rd email message using Python</h1>"
userName='teaching807#gmail.com'
password='teaching807299'
connection = smtplib.SMTP(host,port)
connection.ehlo()
connection.starttls()
_from=userName
_to=userName
connection.login(userName,password)
tmessage = MIMEMultipart("alternative")
tmessage['Subject']="Html Message"
tmessage['From']=_from
tmessage['To']=_to
plain_message = "This is a plain message"
html_message="""<html><body><h1>Students Marks</h1><p>These are the students
Marks</p></body></html>"""
msg1=MIMEText(html_message,'html')
msg2=MIMEText(plain_message,'plain')
tmessage.attach(msg1)
tmessage.attach(msg2)
connection.sendmail(_from,_to,tmessage.as_string())
connection.quit()
In the inbox only msg2 can be seen
By adding two parts, you're offering alternatives. From the python docs:
According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred.
You're adding the plain text last, making that the prefered one. You'll never see both the plain and html.
According to the bottom part of this documentation, the type "alternative" is simply that, to provide an alternative plain text when HTML is not supported for whatever reason.
You're only viewing one message because your email account/browser supports html.
You will only ever see one email, because only one is sent. What you view depends upon what type of data your email/browser can support.
try removing "alternative" from tmessage, it works for me in Outlook.
tmessage = MIMEMultipart()

Python: What is the correct MIME type for attaching html file to email

I've got a script that sends emails with html content in them.. works as expected...
I'm having trouble sending an attachment with the email.
The attachment is an html file stored in the active directory of the script... "test.html"
How do I attach the html file to the email? I've tried snippets from various other posts I've found relating to this, but each returned the same output of "no such file or directory".
code as follows:
import smtplib
import os
import email.encoders
import email.mime.text
import email.mime.base
import mimetools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == Outgoing email address
# you == Recipient's email address
me = "secret"
you = "secret"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "TEST"
msg['From'] = me
msg['To'] = you
emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')
# Create the body of the message (a plain-text and an HTML version).
html = """\
<html>
<head></head>
<body>test</p>
</body>
</html>"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"
f = file(filename)
attachment = MIMEText(f.read(), _subtype='html')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
msg.attach(attachment)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
# mail.login(username, password) to Outgoing email account
mail.login('secret', 'secret')
mail.sendmail(me, you, msg.as_string())
mail.quit()
i've updated my code in hopes to get this question back on topic... i've made a little progress with the help of Dirk and this link:
Attach a txt file in Python smtplib...
I've been able to physically send an attachment now, but the attachment is still coming through as a text type of file of sort and does not open as the original html file does.
So to reword my question... What is the corrective action for changing the MIME type of this code to correctly attach an .html file to an html based email?
The relative path and directory of my py script and the html file needed to be sent is as follows:
C:\CHRIS\ServerStatus\
This is the output i'm receiving with the code I have:
This is the way the html doc looks outside of the email script (The way it's supposed to look):
I would encourage you to use a library rather than deal with the -rather unpythonic- built-in mail modules, such as the highly recommended envelopes:
https://tomekwojcik.github.io/envelopes/index.html
install with:
pip install envelopes
Python code:
import os
from envelopes import Envelope
filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"
envelope = Envelope(
from_addr=(me),
to_addr=(you),
subject=u'Test',
text_body=u'Plain text version',
html_body=html
)
envelope.add_attachment(filename)
envelope.send('smtp.gmail.com', login='secret', password='secret', tls=True)

Amazon SES Friendly From Header

I'm having some trouble getting Amazon SES to display a friendly FROM header. The issue seems to be that SES is inserting an additional from header before mine.
I'm using Python boto, and sending a MIME message using the send_raw_email method.
to_str = 'Name <name#domain.com>'
from_str = 'Name2 <name2#domain.com>'
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Hello World'
msg['From'] = from_str
msg['To'] = to_str
msg.attach(MIMEText(em_plain, 'plain'))
msg.attach(MIMEText(em_html, 'html'))
ses_connection.send_raw_email(msg.as_string(), source=from_str, destinations=to_str)
What I get in the headers of the message that's delivered looks like this:
Subject: Hello World
Date: Thu, 9 Apr 2015 20:47:31 +0000
Message-ID: <blah-blah-blah#email.amazonses.com>
From: name2#domain.com
X-SES-Outgoing: 2015.blah.blah
Feedback-ID: 1.us-east-1.blah//blah=:AmazonSES
From: "Name2" <name2#domain.com>
To: "Name" <name#domain.com>
The result is that the user's mailbox does not display the friendly name. Plenty of info on the web says this is possible, but I can't get this working.
Looking into this further, if I omit the optional source parameter on the call to send_raw_email, the call fails with an error about a missing From header ... despite the fact that it has been set within the MimeMultipart object.
So, I think there are two issues - first, if I pass a friendly From header in the source parameter, it gets stripped down to just the email address. Second, the From that's in the MimeMultipart isn't recognized.
Figured it out.
Order of operations on the MIMEMultipart object matters.
You have to set the From header first, then the To, then the Subject.
If you do it in this order, then you can safely leave out the optional source and destination parameters on the send_raw_email call.
Would seem to be a limitation/issue with SES, as many other mail servers do not require the From header to come before the Subject.

Python: Attaching MIME encoded text file

After a bunch of fiddling, I finally hit upon the magical sequence to attach a text file to an email (many thanks to previous posts on this service).
I'm left wondering what the lines:
attachment.add_header('Content-Disposition'. . .)
--and--
e_msg = MIMEMultipart('alternative')
actually do.
Can someone unsilence the Mimes for me please (sorry couldn't resist)
import smtplib
from email import Encoders
from email.message import Message
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_server = "1.2.3.4"
smtp_login = "account"
smpt_password = "password"
server = smtplib.SMTP(smtp_server)
server.login(smtp_login,smtp_password)
f = file("filename.csv")
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="filename.csv")
e_msg = MIMEMultipart('alternative')
e_msg.attach(attachment)
e_msg['Subject'] = 'Domestic Toll Monitor'
e_msg['From'] = smtp_account
body = 'Some nifty text goes here'
content = MIMEText(body)
e_msg.attach(content)
server.sendmail(smtp_from, smtp_to, e_msg.as_string())
Basically, MIME is the specification defining email structure. The Multipart structure is designed to allow for multiple types of messages and attachments to be sent within the same message. For example, an email might have a plain text version for backwards compatibility and a rich text or html formatted message for modern clients. Attachments count as a "part", and thus require their own header. In this case, you're adding a "Content-Disposition" type header for the attachment. If you're really interested in what that means, you can read the specification here. As for the "Alternative portion, you're setting the message to multipart and defining the types of parts that you have attached and how the client needs to handle them. There are some standard presets defining various scenarios, but Alternative is something of a wildcard, used when there is a part whose type might not be recognized or handled by most clients. For the record, I believe you also could have used a "Mixed" type. The nice thing about MIME is that while it is complicated, its thoroughly defined and its very easy to look up the specification.

HTML email in Python

I'm trying to send an HTML email using smtplib. But I need the HTML content to have a table that is populated using values from a dictionary. I did look at the examples on the Python website. But it doesn't explain how to embed Python code within HTML. Any solutions/suggestions?
I also looked at this question. Can I just format it this way?
.format(dict_name)
From your link:
Here’s an example of how to create an HTML message with an alternative
plain text version: 2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my#email.com"
you = "your#email.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
and the sending section of it:
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
Edit 2022: for new comers, please advise with python’s latest stable release docs.
What you need is a template engine. That is, you need a python library that reads a file written in both HTML and code, interprets the code written within the HTML file (e.g. code that retrieves values from a dictionary), and then produces an HTML file for you.
The python wiki seems to have some suggestions

Categories