I'm trying to send an email using Python and used the following code:
import smtplib
import datetime
SERVER = "localhost"
PORT = 1025
FROM = "me#mydevice.com"
TO = ["myemailaddress#something.com"]
SUBJECT = "test"
dt = datetime.datetime.now()
TEXT = "blabla bla # " + str(dt)
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ",".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER, PORT)
server.sendmail(FROM, TO, message)
server.quit()
Not having any STMP server already installed/setup, I simply used this:
python -m smtpd -n -c DebuggingServer localhost:1025
The code seems to run fine, no errors, and the server even notifies me with this:
---------- MESSAGE FOLLOWS ----------
From: me#mydevice.com
To: myemailaddress#something.com
Subject: test
X-Peer: 127.0.0.1
blabla bla # 2014-01-29 14:44:37.219724
------------ END MESSAGE ------------
'myemailaddress#something.com' is, of course, a representation of a real, existing email address while 'me#mydevice.come' is made up.
But no email arrives at myemailaddress#something.com...
Am I missing something obvious here?
I read somewhere (sorry but cannot find it anymore) that services likes gmail may well block emails coming from non-static IP addresses. Could that be what is going on here?
According to python documentation on the smtpd module:
class smtpd.DebuggingServer(localaddr, remoteaddr)
Create a new debugging server. Arguments are as per SMTPServer.
Messages will be discarded, and printed on stdout.
So the module doesn't actually send an email. It prints it in the terminal.
Related
Very new to python. I am in need of a sample code in python that would allow me to get the list of alerts/alarms configured in Grafana. Thanks for your help.
I have tried googling and searching on github but what I could get was a code to create new alarms. But I just want to get the list of alarms. Don't really know how to go about it.
There exists a python package for this exact usage grafana_alerts. You want to get Grafana alerts onto your python script using some sort of API.
Installation: pip install grafana_alerts
You'll have to create a config file
/etc/grafana_alerts/grafana_alerts.cfg
#
# Grafana alerts configuration file.
#
# The URL where grafana server is listening. It must finish with the character '/' (default value: http://localhost:3130) grafana_url =
http://yourgrafanaserver.com/grafana/
# Grafana token with viewer access (default value: empty string) grafana_token =
qwertysDssdsfsfsdfSFsfsfEWrwrwERwrewrwrWeRwRwerWRwERwerWRwerweRwrEWrWErwerWeRwRwrewerr==
# email to use as alert sender (default value: grafana-alert#localhost) email_from = alert#example.com
# smtp server to use (default value: localhost) smtp_server = localhost
# smtp server host to use (default value: 25)
# if port is not 25, starts a tls session. smtp_port = 25
# smtp server username to use if it is needed. Optional. Leave it commented if not used. (default value: no username)
#smtp_username = my_smtp_username
# smtp server password to use if it is needed. Optional. Leave it commented if not used. (default value: no password)
#smtp_password = my_smtp_password
Add the task to execute it for example each 3 minutes:
*/3 * * * * grafana_alerts
Read more about the package and repository.
I'm modifying a script in python to run in securecrt 8.5.2 in order to backup the running-config of some cisco ASR9K equipment I have in charge, but the script seems to end abruptly after the second sucessful ssh2 hop (2nd tab) and does not send the commands I scripted (the exit in this specifical example), here's the code I have, as I'd said it's a modified version of the one's in vandyke page for opening ssh2.
One important thing is that I have to tab each session of each individual routers, because it doesn't permit doing an ssh direct from the active cli, so I had to improvise and implement this "connect in TAB", I'm suspecting that the secureCRT doesn't know if it is in the new tab I've opened so, it doesn't know where to send the commands.
I was playing with the line 30, but it doesn't seem to have any effect. I was changing the expected text, but it doesn't seem to recognize the correct tab or doesn't read the correct one.
Personal Background: A complete beginner in the python language.
# $language = "python"
# $interface = "1.0"
# Connect to an SSH server using the SSH2 protocol. Specify the
# username and password and hostname on the command line as well as
# some SSH2 protocol specific options.
host = "X.X.X.a"
host2 = "X.X.X.b"
def main():
crt.Screen.Synchronous = True
# Prompt for a username and password instead of embedding it in a script...
#
usr = crt.Dialog.Prompt("Enter the user name for" + host, "Username", "", True)
passwd = crt.Dialog.Prompt("Enter TACACS+ for" + host, "Login", "", True)
# Build a command-line string to pass to the Connect method.
cmd = "/SSH2 /L %s /PASSWORD %s /C AES-128-CTR /M SHA1 %s" % (usr, passwd, host)
crt.Session.Connect(cmd)
crt.Screen.WaitForString("X.X.X.a#")
crt.Screen.Send("copy running-config tftp:\r")
crt.Screen.WaitForString("Host name or IP address (control-c to abort): []?")
crt.Screen.Send("tftpserver.com\r")
crt.Screen.WaitForString("Destination file name (control-c to abort): [running-config]?")
crt.Screen.Send("X.X.X.a_running_config\r")
crt.Screen.WaitForString("X.X.X.a")
cmd2 = "/SSH2 /L %s /PASSWORD %s /C AES-128 /M SHA1 %s" % (usr, passwd, host2)
crt.Session.ConnectInTab(cmd2)
crt.Screen.WaitForString("X.X.X.b#")
crt.Screen.Send("exit\r")
main()
crt.Session.ConnectInTab(cmd2)
It connects to the equipment in a new tab, but what I expect is that the script will keep doing the same it did for the host1 (X.X.X.a) and send the same boring stuff to the host2 (X.X.X.b) via ssh2 tab, and continue the itterative process until I do this for all the equipments I need.
Thanks for reading me.
Well it's not even funny easy was to solve this very sub-optimal code or script but it was not much of a problem, the only thing is that I had to dissconect to the previous session when I inyected all the commands, so in order to put the cursor on the new tab, the previous session must be dissconected first.
The solution?
crt.Session.Disconnect()
i have a couple issues with sending Email with Python using my own SMTP/IMAP Server.
Here's the code :
import sys
import imaplib
import smtplib
import email
import email.header
import datetime
smtp_session = smtplib.SMTP(mail_server)
try:
smtp_session.ehlo()
except :
err = sys.exc_info()[0]
message = """\
From: %s
To: %s
Subject: %s
%s""" % (email_from, ", ".join([email_to]), "subject", "body")
try:
smtp_session.sendmail(email_from, [email_to], message)
smtp_session.quit()
except:
err = sys.exc_info()[0]
if err != "" or err !=None:
NagiosCode = 2
NagiosMsg = "CRITICAL: Script execution failed : " + str(err)
Ok so for the two issues i have:
When i send a mail from my script i need the mail to appear in the "sent items" diretory of my mail box who send it.
Second issue i have : When sending my mail i catch this exception :
<class 'smtplib.SMTPException'>
EDIT : Exception trace :
File "checkIMAP_client.py", line 153, in <module>
smtp_session.login(login, password)
File "/usr/lib64/python2.6/smtplib.py", line 559, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
EDIT :
It seems my SMTP server doesn't require authentification.
But the program still returns me an empty exception.
Code is updated.
So for the two issues i had, i found the answers thanks to the above comments :
Putting my sent e-mail via SMTP in the right mailbox in the Sent directory :
https://pymotw.com/2/imaplib/
Look for "Uploading messages"
Exception issue :
I had no auth methods set on my SMTP server.
I have a small application under Linux to receive an email with the use of smtpd.SMTPServer. Here is the small test code:
class CustomSMTPServer(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'Receiving message from:', peer
print 'Message addressed from:', mailfrom
print 'Message addressed to :', rcpttos
print 'Message length :', len(data)
return
server = CustomSMTPServer(('0.0.0.0', 25), None)
asyncore.loop()
I have the following issues:
(1) When using this piece of code, the computer sending the email gets the following message:
502 Error: command "EHLO" not implemented
so the server cannot reply correctly to receive further data / communicate with the email-sending computer (which I assume is the client).
Shouldn't such a basic thing like EHLO be implemented in a Ubuntu installation in the first place? Why is it not implemented?
(2) I figured that EHLO can be installed by installing postfix in Ubuntu. I did that and the same test call went on, but stopped later with a different error:
Client: RCPT TO: XXX#YYY.com
Server: 554 5.7.1 <XXX#YYY>: Relay access denied
(3) At later times, after doing some more other tests, I got the error from the test code itself:
error: [Errno 98] Address already in use
It turns out that the used IP address was already in use as could be seen with
netstat -lnpt
of which the case was the running postfix. After stopping the postfix service the address was no longer in use, but of course it was back to issue #1:
502 Error: command "EHLO" not implemented
I would like to be able to use a SMTPServer to receive an email message
1. without the need to install postfix
2. with the use of asyncore
If there are any ideas of how to make this possible in an easy and simple way using python libraries that would be great!
Cheers
Alex
1) Postfix is an SMTP server, it has nothing to do with python's smtpd EHLO implementation. If you want your custom SMTP server, you don't need postfix, so feel free to remove it.
2) EHLO is a ESMTP command, not SMTP, standard smtpd python module implements SMTP, therefore it doesn't have an EHLO implementation.
Try this.
Of course, it does not implement the EHLO command, but makes it treat it the same as the HELO command. Of course, it might only get you past the first stumbling block, however if the rest of the smtp commands are compatible it might get you by:
You will probably find the smtpd.py file in /usr/lib/python2.7
def smtp_HELO(self, arg):
if not arg:
self.push('501 Syntax: HELO hostname')
return
if self.__greeting:
self.push('503 Duplicate HELO/EHLO')
else:
self.__greeting = arg
self.push('250 %s' % self.__fqdn)
#copy the above function and rename it smtp_EHLO
def smtp_EHLO(self, arg):
if not arg:
self.push('501 Syntax: HELO hostname')
return
if self.__greeting:
self.push('503 Duplicate HELO/EHLO')
else:
self.__greeting = arg
self.push('250 %s' % self.__fqdn)
Also, I note the python3.5 version of the same library looks like it supports EHLO, so maybe you could try and use python3. But apparently python3 is not backwards compatible it seems - so good luck.
I'm getting this error:
raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused:
{'example#hotmail.com': (550, '5.1.1 : Recipient
address rejected: hotmail.com')}
when trying to run my python script.
Regardless of what recipient address I put in, it will still give me the same error. I have postfix's configuration installed as local and it properly recognizes 'localhost' but not any of the sender addresses. This is my code:
import smtplib
def sendEmail(addressFrom, addressTo, msg):
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(addressFrom, addressTo, msg)
server.quit()
msg = "This is the content of the email"
addressFrom = ""
addressTo = "example#hotmail.com"
sendEmail(addressFrom, addressTo, msg)
And this is the main.cf file for postfix. Looking at it now,mydestination is only set to local addresses, could that be the issue?
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific: Specifying a file name will cause the first
# line of that file to be used as the name. The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
myhostname = user-desktop
**mydomain = hotmail.com**
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
**mydestination = user-desktop, localhost.$mydomain www.$mydomain**
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = loopback-only
default_transport = error
relay_transport = error
inet_protocols = ipv4
Thank you in advance
I faced a similar issue in my python script.
Use the following command to change the configuration of Postfix to Internet Site
sudo dpkg-reconfigure postfix
Change the Postfix configuration to Internet Site. This will resolve your problem and can send mail to any mail address.
Your code looks OK. This is very likely a configuration issue with Postfix.
Hi I had a similar problem. I was getting the error:
(550, '5.7.1 Client does not have permissions to send as this sender')
Turning on TLS, adding the ehlo commands explicitly fixed the problem for me. Hope it helps.
def mail(msg):
email_server = "mail.some-server.com"
sender = "me#some-server.com"
to = "you#some-server.com"
subject = "How about those Mariners!"
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
text = msg
message = headers + text
mailServer = smtplib.SMTP(email_server)
mailServer.set_debuglevel(1)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login('user', 'pass')
mailServer.ehlo()
mailServer.sendmail(sender, to, message)
mailServer.quit()