I use zabbix as a monitor, but i have a problem,
when the zabbix send Alarm email,then the email would send by SMS to my iphone.
If the email title is Japanese or Chinese.
the sms is Disorder Code. Here is the scripts,how to modify it?
#!/usr/bin/python26
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
mail_host = 'smtp.189.cn'
mail_user = 'tom_a'
mail_pass = '123456'
mail_postfix = '189.cn'
def send_mail(to_list,subject,content):
me = mail_user+"<"+mail_user+"#"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='utf-8')
msg['Subject'] = subject
msg['From'] = me
msg['to'] = to_list
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me,to_list,msg.as_string())
s.close()
return True
except Exception,e:
print str(e)
return False
if __name__ == "__main__":
send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
You are making this much more complicated than it needs to be. Instead look at the SMS functionality built right into Zabbix and use that. Instead of trying to hack into the email sending functionality (I think), just write yourself a script to work with the SMS provider of your choice.
Then add this to your alert options for the triggers you care about. For example, you might want it to run only for Disaster level triggers.
Related
Everytime I send an email with this function, it doesn't add the subject and the message to the right fields, but instead of that, it adds it to the 'from:' or something.
Here's the image of it.
Any idea how this can be fixed? Thanks for answer
import smtplib
## NON-ANONYMOUS EMAIL
def email():
# Parts of an email
SERVER = 'smtp.gmail.com'
PORT = 587
USER = 'something#gmail.com'
PASS = 'something'
FROM = USER
TO = ['something#riseup.net']
#SUBJECT = 'Test'
MESSAGE = 'Test message.'
# Connects all parts of email together
message = "From: %s\r\n To: %s\r\n %s" % (FROM, ", ".join(TO), MESSAGE)
# Sends an email
email = smtplib.SMTP()
email.connect(SERVER,PORT)
email.starttls()
email.login(USER,PASS)
email.sendmail(FROM, TO, message)
email.quit()
email()
You cannot have a space after the \r\n. An email header line is continued by indenting it, so your code is creating a really long From: header with all the data you are trying to put in different fields.
Anyway, manually gluing together snippets of plain text is a really crude and error-prone way to construct an email message. You will soon find that you need the various features of the Python email module anyway (legacy email is 7-bit single part ASCII only; you'll probably want one or more of attachments, content encoding, character set support, multipart messages, or one of the many other MIME features). This also coincidentally offers much better documentation for how to correcty create a trivial email message.
Following on from #tripleee suggestion to use the email module, here's a basic example using your current code:
import smtplib
from email.mime.text import MIMEText
## NON-ANONYMOUS EMAIL
def email():
# Parts of an email
SERVER = 'smtp.gmail.com'
PORT = 587
USER = 'something#gmail.com'
PASS = 'something'
FROM = USER
TO = ['something#riseup.net']
SUBJECT = 'Test'
# Create the email
message = MIMEText('Test message.')
message['From'] = FROM
message['To'] = ",".join(TO)
message['Subject'] = SUBJECT
# Sends an email
email = smtplib.SMTP()
email.connect(SERVER,PORT)
email.starttls()
email.login(USER,PASS)
email.sendmail(FROM, TO, message.as_string())
email.quit()
Notice how much easier it is to define the parts of the email using keys like message['Subject'] instead of attempting to build a string or 'gluing parts together' as tripleee put it.
The different fields (From, To, Subject, et cetera) you can access are defined in RFC 2822 - Internet Message Format.
These documents are not easy to read, so here's a list of some of the fields' keys you can use: To, From, Cc, Bcc, Reply-To, Sender, Subject.
You cannot have a space after the \r\n. An email header line is continued by indenting it, so your code is creating a really long From: header with all the data you are trying to put in different fields.
As triplee and the RFC-2822 document says, if you are wanting to build the email string manually look at the field definitions in that document which look similar to this example:
from = "From:" mailbox-list CRLF
You can translate this into Python code when building an email string like so:
"From: something#riseup.net \r\n"
I was able to get mine to work using:
("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s"
% (gmail_user, recipient, subject, body))
Im a newbie to python and having a problem.
I want to attach a function to the body of smtp message.
the function return result of information, I need those results in my body message so other can see it when they receive the email not sure how to do it.
Any help for this newbie would be great!!
Here my code:
import smtplib
# For guessing MIME type
import mimetypes
# Import the email modules we'll need
import email
import email.mime.application
# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Greetings'
msg['From'] = 'test1#mail.com'
msg['To'] = 'test2#mail.com'
# The main body is just another attachment
body = email.mime.Text.MIMEText("""Hello, how are you? I am fine.
This is a rather nice letter, don't you think?""")
msg.attach(body)
# send via Gmail server
# NOTE: my ISP, Centurylink, seems to be automatically rewriting
# port 25 packets to be port 587 and it is trashing port 587 packets.
# So, I use the default port 25, but I authenticate.
s = smtplib.SMTP('localhost', 25)
s.starttls()
s.login(username, password)
s.sendmail('To', 'From', msg.as_string())
s.quit()
if len(argument1) > 0:
startThebootstrap.function (argument1, t.argument2 ())
The current body only accept text, i want to change this to obtain a function result.
Is this possible?
Im using argsparse to command the section i want, and the result appear on CMD, i want those result in my email.
I have a command which start the display of the result.
1. You want to send some python objects (function arguments or results)
A general way is to use a "serializer" to make objects (not functions) to strings.
import pickle # pickle is not a save serializer. you can build virusses with it.
string = pickle.dumps(object) # string can be attached to the email.
object = pickle.loads(string)
pickle can transport virusses and functions but these two can not:
import json
string = json.dumps(object).encode('utf-8') # string can be attached to the email.
object = json.loads(string.decode('utf-8'))
import ast
string = repr(["smile!"])
object = ast.literal_eval(string)
2. you want to send the source code of a function
import linecache
def function():
return 5
source_lines = inspect.getsourcelines(function)[0]
source_code = ''.join(source_lines) # make the list to a string
now you can add source_code to the body of the mail.
Let me know of your ideas about this and whether you understand it.
I am using the following code to send email from unix.
Code
#!/usr/bin/python
import os
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "myname#company.com")
p.write("To: %s\n" % "yourname#company.com")
p.write("Subject: My Subject \n")
p.write("\n") # blank line separating headers from body
p.write("body of the mail")
status = p.close()
if status != 0:
print "Mail Sent Successfully", status
sendMail()
I am not sure how to add attachment to this email (attachment being on a different directory /my/new/dir/)
Sendmail is an extremely simplistic program. It knows how to send a blob of text over smtp. If you want to have attachments, you're going to have to do the work of converting them into a blob of text and using (in your example) p.write() to add them into the message.
That's hard - but you can use the email module (part of python core) to do a lot of the work for you.
Even better, you can use smtplib (also part of core) to handle sending the mail.
Check out http://docs.python.org/2/library/email-examples.html#email-examples for a worked example showing how to send a mail with attachments using email and smtplib
Use the email.mime package to create your mail instead of trying to generate it manually, it will save you a lot of trouble.
For example, sending a text message with an attachment could be as simple as:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['From'] = 'fromaddress'
msg['To'] = 'toaddres'
msg['Subject'] = 'subject'
msg.attach(MIMEText('your text message'))
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), 'subtype')
attachment['Content-Disposition'] = 'attachment; filename="%s";' % filename
msg.attach(attachment)
message = msg.as_string()
Then you can write the message to sendmail, or use smtplib to send it.
'subtype' should either be replaced with the mime subtype of the attached document, or left out to send the attachment with the default type of application/octet-stream. Or if you know your file is text, you can use MIMEText instead of MIMEApplication.
I normally use the following to send a file "file_name.dat" as attachment:
uuencode file_name.dat file_name.dat | mail -s "Subject line" arnab.bhagabati#gmail.com
I'm a Python junior, so keep that in mind. In a Python script, I need to set a Return-Path address that is different than the sender's address. (I'm using Gmail as SMTP server.)
I've done lots of searching on this question and found plenty of "answers", but no solutions. I tried this link Setting Return-Path with Python sendmail for a MIME message but it's not working for me at all. I can change the "To:" address that the email recipient sees, but when they click "Reply", it's back to the sending email address again.
This is the function that I'm trying to write. It works well enough, except that I need to force a different Return-Path.
#!/usr/bin/python
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import sap_mailserverdata as sf
def send_mail(sent_to, subject, body_text, sent_from_addr='', sent_from_name='', files=[], cc=[], bcc=[]):
"""Send emails with or without attachments."""
assert type(sent_to)==list
assert type(files)==list
assert type(cc)==list
assert type(bcc)==list
message = MIMEMultipart()
message['From'] = sent_from_addr
message['To'] = COMMASPACE.join(sent_to)
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
message['Cc'] = COMMASPACE.join(cc)
message.preamble = 'You need a MIME enabled mail reader to see this message.\n'
message.attach(MIMEText(body_text, 'html'))
for f in files:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
message.attach(part)
addresses = []
for x in sent_to:
addresses.append(x)
for x in cc:
addresses.append(x)
for x in bcc:
addresses.append(x)
mail_server = smtplib.SMTP(sf.server, sf.server_port)
mail_server.ehlo()
mail_server.set_debuglevel(1)
mail_server.starttls()
mail_server.login(sf.username, sf.password)
mail_server.sendmail(sent_from_addr, addresses, message.as_string())
mail_server.quit()
What am I missing with this function to be able to reliably specify a different replyto Return-Path?
Reply-to and return path are two distinct beasts. See the RFC.
You can set Reply-to with:
msg['reply-to'] = 'smith#acme.com'
The return-path is set by the MTA to the address that receives bounces. It is controlled by the server administrator, so unless you work for Google I don't think this is under your control.
Most of the time one is after "Reply-to"; if you really need to change the return path you must use a SMTP server under your control and google for how to do this for the specific MTA you are using - many will have a white list of users and/or hosts that can override the return path.
i'm new with python..
Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.
So, i've found this tutorial and adapted it with the gmail authentication (tutorial found here)
The code i have atm, is that:
def createhtmlmail (html, text, subject):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
return msg
import smtplib
f = open("/path/to/html/version.html", 'r')
html = f.read()
f.close()
f = open("/path/to/txt/version.txt", 'r')
text = f.read()
subject = "Prova email html da python, con allegato!"
message = createhtmlmail(html, text, subject)
gmail_user = "thegmailaccount#gmail.com"
gmail_pwd = "thegmailpassword"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(gmail_user, gmail_pwd)
server.sendmail(gmail_user, "example#example.com", message)
server.close()
and that works.. now only miss the attachment..
And i am not able to add the attachment (from this post)
So, why there is not a python class like phpMailer for php?
Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed?
Or is because i just didn't find it?
If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?
If you can excuse some blatant self promotion, I wrote a mailer module that makes sending email with Python fairly simple. No dependencies other than the Python smtplib and email libraries.
Here's a simple example for sending an email with an attachment:
from mailer import Mailer
from mailer import Message
message = Message(From="me#example.com",
To=["you#example.com", "him#example.com"])
message.Subject = "Kitty with dynamite"
message.Body = """Kitty go boom!"""
message.attach("kitty.jpg")
sender = Mailer('smtp.example.com')
sender.login("username", "password")
sender.send(message)
Edit: Here's an example of sending an HTML email with alternate text. :)
from mailer import Mailer
from mailer import Message
message = Message(From="me#example.com",
To="you#example.com",
charset="utf-8")
message.Subject = "An HTML Email"
message.Html = """This email uses <strong>HTML</strong>!"""
message.Body = """This is alternate text."""
sender = Mailer('smtp.example.com')
sender.send(message)
Edit 2: Thanks to one of the comments, I've added a new version of mailer to pypi that lets you specify the port in the Mailer class.
Django includes the class you need in core, docs here
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', 'from#example.com', 'to#example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file('/path/to/file.jpg')
msg.send()
In my settings I have:
#GMAIL STUFF
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'name#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
Just want to point to Lamson Project which was what I was looking for when I found this thread. I did some more searching and found it. It's:
Lamson's goal is to put an end to the hell that is "e-mail application development". Rather than stay stuck in the 1970s, Lamson adopts modern web application framework design and uses a proven scripting language (Python).
It integrates nicely with Django. But it's more made for email based applications. It looks like pure love though.
Maybe you can try with turbomail python-turbomail.org
It's more easy and useful :)
import turbomail
# ...
message = turbomail.Message("from#example.com", "to#example.com", subject)
message.plain = "Hello world!"
turbomail.enqueue(message)
I recommend reading the SMTP rfc. A google search shows that this can easily be done by using the MimeMultipart class which you are importing but never using. Here are some examples on Python's documentation site.