I have a Python script that loops through a list of 8 different machines and does a copy, execute, and test. I would like to receive an email after each loop. **I'm not sure what to google for this. I would appreciate any ideas that will help me with my task.
I am aware of the smtplib module, just not how to perform a certain task with it.
I did indeed check the handy search engine and found no previous questions that provided answers
Question: how would one break in the middle of a loop, send an email, then continue with the loop??????
I have an email when the script starts and an email when the script ends. I just want to be notified as the script progresses or if it fails.
Thank you in advance.
You're looking for Python's smtp library.
The example from the documentation is this:
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.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Use the built-in email package to create your message if there's anything nonstandard you need to do with MIMEtypes/etc. Use the built-in smtplib package to send it (and create it if you don't have to do anything fancy).
Related
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.
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...")
Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.
Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.
I heard that getpass.getpass() can be used to hide the input.
Here is my code:
import smtplib
import getpass
import sys
print('Starting...')
SERVER = "localhost"
FROM = "my#email.com"
while True:
password = getpass.getpass()
try:
smtpObj = smtplib.SMTP(SERVER)
smtpObj.login(FROM, password)
break
except smtplib.SMTPAuthenticationError:
print("Wrong Username/Password.")
except ConnectionRefusedError:
print("Connection refused.")
sys.exit()
TO = ["your#email.com"]
SUBJECT = "Hello!"
TEXT = "msg text"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")
But when I run my code, here is the output:
Starting...
/Nothing else appears/
I know the default prompt for getpass() is 'Password:' but I get the same result even when I pass it a prompt string.
Any suggestions?
EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.
For PyCharm 2018.3
Go to 'Edit Configurations' and then select 'Emulate terminal in output console'.
Answer provided by Abhyudaya Sharma
The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by getpass)
Running the code via a command prompt should work
I am currently trying to read messages cat channels Twitch. For this, I have read some guides and I learned it had to go through the IRC Twitch. I then found a few lines of simple code.
import socket
import string
HOST="irc.twitch.tv"
PORT=6667
NICK="TwitchUsername"
IDENT="TwitchUsername"
REALNAME="TwitchUsername"
CHANNEL="#ChannelNameHere"
PASSWORD="OAuth Password here" #From http://twitchapps.com/tmi/
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("PASS %s\r\n" % PASSWORD)
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
s.send("JOIN %s\r\n" % CHANNEL)
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if len(line) > 3:
print line
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
However, authentication does not proceed as planned, since I get the following message:
[':tmi.twitch.tv', 'NOTICE', '*', ':Login', 'unsuccessful']
I am using a valid OAuth Chat Password, and I see no reason that justifies this failure. Do you also have an error when you try with your username? Or do you have an idea of the problem please?
Your OAuth password needs to be sent as:
PASS oauth:twitch_oauth_token
which means that if you are putting in your token in the PASSWORD variable without the oauth: prefix, you should amend the pass line to:
s.send("PASS oauth:%s\r\n" % PASSWORD)
I was seeing the same :tmi.twitch.tv NOTICE * :Error logging in.
As noted in the readme "Your nickname must be your Twitch username in lowercase".
My issue was not making the NICK exactly my twitch username in lowercase (Not a very informative notice. So hopefully this saves someone else some time...).
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.