Pass Print messages in Python to email - python

I've written a python script that has several print statements in it. I'd like to pass these print statements to an email that the script will send me after it has finished running. Is this possible?
Below is my attempt, it errors out at the deleted =
import arcpy, os
arcpy.DeleteRows_management(r"C:\GIS_Work\StreetsTesting\Lake George.shp")
deleted = print "The rows have been deleted from Lake George"
# Send Email when script is complete
SERVER = "my.mailserver.com"
FROM = "from#email.com>"
TO = "to#email.com>"
SUBJECT = "The Script Has Completed"
MSG = deleted
# Prepare actual message
MESSAGE = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, MSG)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, MESSAGE)
server.quit()

Related

How to Have "Destination Host Unreachable" when pinging return a value of 1 and not 0

I am using python to code a program that will ping a device, and do nothing if it gets a response back from the device, but if it does not receive any response, it will send me an email to notify me that the device may be down. However, as has been mentioned on here before, when the response from the ping is "Destination Host Unreachable," the return value is 0, which is the same as if it received a response. So what I'm looking for is help with how to discern the Destination Host Unreachable from the actual response so I can have an email sent to me under that condition (since it means the device is most likely down).
import platform
import subprocess
import smtplib
import time
#Delay to wait for Rigs to Boot
#time.sleep(600)
a = 1
while 1==1:
#Ping other PC's
def myping(host):
parameter = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', parameter, '1', host]
response = subprocess.call(command)
if response == 0:
return True
#Will Send email if response from ping is false (aka not pingable/down)
else:
gmail_user = 'email'
gmail_password = 'password'
sent_from = gmail_user
to = ['recepient']
subject = 'subject'
body = 'body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")
except Exception as ex:
print ("Something went wrong….",ex)
#delay so i dont recieve spam emails while the 'while' loop runs
time.sleep(43000)
print(myping("ip to ping"))
Thank you for the help in advance.
You obviously can't change the behavior of ping. However, you can certainly use subprocess.check_output, which returns the output of the command, and parse that.
Using ping like this is not particularly useful. There are many reasons why you can't reach a remote host. Perhaps your local network is down, or your router has died, or your cable has been unplugged.

How to make a python script automatically send an email when certain data is changed?

So basically, I made a python script to send me an email containing my public IP every 12 hours. My goal is to make it automatically send an email only when my IP changes. I would love it if you guys could give me some help.
There's my code:
from json import loads
from urllib.request import urlopen
import time
import smtplib
while True:
data = loads(urlopen("http://httpbin.org/ip").read())
print ("The public IP is : %s" % data["origin"])
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo()
server_ssl.login("fromemail#gmail.com", "password")
msg = """From: Automated Python Script <fromemail#gmail.com>
To: First Last <toemail#gmail.com>
Subject: SMTP e-mail test
""" + data["origin"] + """
"""
server_ssl.sendmail("fromemail#gmail.com", "toemail#gmail.com", msg)
print ("Successfully sent email!")
time.sleep(720)
except SMTPException:
print ("Something went wrong...")
By the way, it's in python 3.
I'd really like it to send me an email automatically when my public ip changes instead of sending me an email with probably the same IP every 12 hours.
Thanks!
This checks the change in public ip to whichever time interval you want based on the value you set to x. If your public ip changes frequently then set lower values of x and if it changesless often you can set it accordingly
from json import loads
from urllib.request import urlopen
import time
import smtplib
data_prev = loads(urlopen("http://httpbin.org/ip").read())
prev_public = data_prev["origin"]
while True:
data_next = loads(urlopen("http://httpbin.org/ip").read())
next_public = data_next["origin"]
print ("The public IP is : %s" % data["origin"])
if(next_public != prev_public):
prev_publi = next_public
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo()
server_ssl.login("fromemail#gmail.com", "password")
msg = """From: Automated Python Script <fromemail#gmail.com>
To: First Last <toemail#gmail.com>
Subject: SMTP e-mail test
""" + data["origin"] + """
"""
server_ssl.sendmail("fromemail#gmail.com", "toemail#gmail.com", msg)
print ("Successfully sent email!")
time.sleep(x) # set x to whichever value you want
#time.sleep(720)
except SMTPException:
print ("Something went wrong...")

Using function to send gmails via python

Below are 2 code blocks. The first will send a message to gmail with the correct subject and sender. However, when I put the first code into a function, the email loses the sender and subject info.
Why is this and how do I fix it?
I would like to be able to call this function from other python scripts to notify me when my job is complete. The function works and runs without error, and the email makes it to my inbox, but I lose the sender info and more importantly, the subject heading.
1st code that runs as expected:
import smtplib
gmail_user = 'name#domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient#domain.com']
subject = "job complete"
body = "python script " + str(name) + " has finished"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
2nd code that loses subject and sender info:
def mailer(subject, body):
import smtplib
gmail_user = 'name#domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient#domain.com']
subject = subject
body = body
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
subject = "job complete"
body = "python script " + str(name) + " has finished"
mailer(subject, body)
It's most likely a line ending issue. Each mail headers is required to end with CRLF (\r\n). The original message string may have contained the correct endings (invisible in the editor) which were subsequently lost during copy/paste to the function version. To ensure that each line is ended correctly, try expressing each as a separate string and joining them with \r\n.
email_text = '\r\n'.join([
'From: %s' % sent_from,
'To: %s' % ', '.join(to),
'Subject: %s' % subject',
'', # Blank line to signal end of headers
body
])

SMTP AUTH extension not supported by server in python

I'm using the following def to send email based on status ,
def sendMail(fbase, status):
server = smtplib.SMTP(config["global"]["smtp_server"], config["global"]["smtp_port"])
server.login(config["global"]["smtp_user"],config["global"]["smtp_pass"])
server.ehlo()
server.starttls()
from_addr = config["global"]["smtp_from"]
if status == "Success":
subject = "%s Uploaded sucessfully" % fbase
msg = "\nHi,\n Video file - %s - uploaded successfully \n Thanks \n Online Team" % fbase
to_addr_list = config["global"]["smtp_to_success"]
else:
subject = "%s Failed to upload" % fbase
msg = "\n Hi!\n Failed to upload %s \n Please check the log file immediatly \n Thanks" % fbase
to_addr_list = config["global"]["smtp_to_failed"]
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + msg
server.sendmail(from_addr, to_addr_list, message)
server.quit()
logger.info("Mail send for status: %s" %(status))
i start getting the following error after Ad admins upgrade the exchange
raise ("SMTP AUTH extension not supported by server.")
SMTPException: SMTP ASMTPExceptionUTH extension not supported by server.
I added
server.ehlo()
server.starttls()
and still getting the same error ,
any advise here
Perform the login step after you've started TLS.
def sendMail(fbase, status):
server = smtplib.SMTP(config["global"]["smtp_server"], config["global"]["smtp_port"])
server.ehlo()
server.starttls()
server.login(config["global"]["smtp_user"],config["global"]["smtp_pass"])
....

send an email with python [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Receive and send emails in python
I tried searching but couldn't find a simple way to send an email.
I'm looking for something like this:
from:"Test1#test.com"#email sender
To:"test2#test.com"# my email
content:open('x.txt','r')
Everything I've found is complicated really: my project doesn't need so many lines.
Please, I like to learn: leave comments in each code and explain
The docs are pretty straitforward:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A simple example, which works for me, using smtplib:
#!/usr/bin/env python
import smtplib # Brings in the smtp library
smtpServer='smtp.yourdomain.com' # Set the server - change for your needs
fromAddr='you#yourAddress' # Set the from address - change for your needs
toAddr='you#yourAddress' # Set the to address - change for your needs
# In the lines below the subject and message text get set up
text='''Subject: Python send mail test
Hey!
This is a test of sending email from within Python.
Yourself!
'''
server = smtplib.SMTP(smtpServer) # Instantiate server object, making connection
server.set_debuglevel(1) # Turn debugging on to get problem messages
server.sendmail(fromAddr, toAddr, text) # sends the message
server.quit() # you're done
This is code I found a while back at Link and modified.

Categories

Resources