Python Include contents of If/else in output not just print - python

I am not that experienced with python, but do some python coding for small jobs. Currently I have a job that opens a log file and pulls any records that are considered errors. This list of errors is then added as part of an email notification. What I would like to do is either include the list or a notification that the list was empty. I have been able to do this in the console, but don't know how to get this added as a parameter in the email.
if errorlist:
print "\n".join(errorlist)
else:
print "No Errors Found"
# Send Email
SMTP_SERVER = {SMTP SERVER}
SMTP_PORT = {SMTP PORT}
sender = {Sender}
password = {Password}
recipient = {Recipient}
subject = "This is the subject line"
errorlist = "<br>" "\n".join(errorlist)
body = "" + errorlist + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + ", " .join(recipient),
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()

The email is sent in this line:
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
The body variable contains the body of your email. In order to add something into the body of the email, it should be added to the string contained by the body variable. Adapting the code you already have added (which successfully prints your desired result), you could replace this line:
body = "" + errorlist + ""
with this:
if errorlist:
body = "\n".join(errorlist)
else:
body = "No Errors Found"

if errorlist:
error_string = "\n".join(errorlist) # assign it to variable
print (error_string) # still print it
else:
error_string = "" # assign blank to error_string
print ("No Errors Found") # still print "no errors found"
.
.
.
body = ""+error_string+"" # 'body = error_string' is the same though
.
.
.
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) # this line you could replace "body" with "error_string" because they are pretty much goign to be equivilant because of the previous comment
You want to assign your error string into a variable, and then use the variable later when constructing the body. Also there is more room for simplification

Related

How to insert var content inside message body of sendmail function

I have the next function:
hostname = os.uname()[1]
def sendmail(sender, receiver, content, user=None, password=None, hostname='localhost', port=25,ssl=False):
smt_server = 'localhost'
port = '25'
sender = 'jenkins#jenkins.com'
receiver = 'test#test.es'
content = "I need to show hostname here" , hostname , "Done."
msg = MIMEText(content)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Simple app script'
try:
s = smtplib.SMTP('localhost', port )
s.sendmail('jenkins#jenkins.com', 'test#test.es', content)
s.quit()
print "Succesfully sent email"
except SMTPException:
print "Error: fail to send email"
Actual result:
AttributeError: 'tuple' object has no attribute 'encode'
Expected result:
The body message of the mail have to be:
I need to show hostname here MyHostname Done.
I'm not sure if i'm using the rigth way, could you help me?
Thanks
You can add strings:
content = "I need to show hostname here" + hostname + "Done."
Try this to make content one string.
content = "I need to show hostname here " + hostname + " Done."

Python - using smtplib to send to multiple recipients

I'm finding it very difficult to modify this code to send to send to multiple recipients, I have tried many variations of the examples already out there. I'm very new to python so any help would be much appreciated.
It is as part of safety system I am designing to alert parents and carers of potential elopement risk for children and adults with ASD.
'''
import time
import serial
import smtplib
TO = 'email#mail.org'
GMAIL_USER = 'email#gmail.com'
GMAIL_PASS = 'passowrd'
SUBJECT = 'Security Alert'
TEXT = 'Movement detected!'
ser = serial.Serial('COM6', 9600)
def send_email():
print("Sending Email")
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(GMAIL_USER, GMAIL_PASS)
header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
header = header + '\n' + 'Subject:' + SUBJECT + '\n'
print header
msg = header + '\n' + TEXT + ' \n\n'
smtpserver.sendmail(GMAIL_USER, TO, msg)
smtpserver.close()
while True:
message = ser.readline()
print(message)
if message[0] == 'M' :
send_email()
time.sleep(0.5)
'''
Send the alert to multiple people.
Have you had a look at this yet? How to send email to multiple recipients using python smtplib?
It looks like you might be dropping some of the pieces of your header too by overwriting them:
header = 'From: ' + GMAIL_USER
Instead of:
header = header + 'From: ' + GMAIL_USER
You might also want to consider using format instead, but I'm already out of my depth on Python :-)

python socket - smtp gmail returns nothing from 'DATA' content line

Code works fine up to writing the 'body' of the DATA command (message content that ends with a line containing nothing but a '.' char).
Socket simply keeps waiting for a .recv() message - no error code returned. If a socket.timeout() option is set, it just prints a 'nothing received' error.
address = "smtp.gmail.com"
port = 465
mailserver = (address, port)
sockplain = socket.socket(socket.AF_INET)
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
sockssl = context.wrap_socket(sockplain, server_hostname=address)
sockssl.connect(mailserver)
def sendToSMTPserver(*vararg):
email_address = "email address goes here"
message_code = "SMTP code goes here e.g. 'RCPT TO'"
mailFrom = "complete message goes here"
if len(vararg) > 1:
message_code, username = vararg
mailFrom = message_code + ":" + username + "\r\n"
else:
message_code = vararg[0]
mailFrom = message_code + "\r\n"
sockssl.send(mailFrom.encode())
print(sockssl.recv(1024))
sendToSMTPserver("EHLO Alice")
sendToSMTPserver("AUTH LOGIN")
sendToSMTPserver(base64.b64encode(username))
sendToSMTPserver(base64.b64encode(password))
sendToSMTPserver("MAIL FROM", "<" + username + ">")
sendToSMTPserver("RCPT TO", "<" + username + ">")
sendToSMTPserver("DATA")
# works fine until here ...
sendToSMTPserver("hangs after sending this line \n.")
The other SMTP server is expecting \r\n for the end of lines, so at the moment you don't have a full stop on its own line, i.e. \r\n.\r\n
So, you need to simply change the last line to
sendToSMTPserver("hangs after sending this line \r\n.")
Adding a extra \r

SMTP sent mail to many recipients but doesn't received it

I've written a Python script to automatically send some information to my friends. I used SMTPlib, it works well if I only sent to me or one additional email.
When I try to send to 17 emails, (including my sender email), then it shows in sent mail on web-based Gmail. I saw that the mail was sent but I didn't receive it. Only the first recipient received the email.
If I reply to all from that mail, then everyone got only that reply.
I can't figure out why they didn't receive it when I sent it from script, I ask my friend check spam, but she didn't find anything.
This is my code:
#!/usr/bin/env python
import smtplib
import csv
from datetime import datetime, timedelta
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'MYBOT#gmail.com'
password = None
with open('pass', 'rt') as f:
password = f.read().strip('\n')
def send_mail(recipient, subject, body):
"""
Send happy bithday mail
"""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
smtp = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp.ehlo()
smtp.starttls()
smtp.ehlo
smtp.login(sender, password)
body = "" + body +""
smtp.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
print "Sent to ",
print recipient
smtp.quit()
def send_happybirthday(recipient):
body = """Happy birthday to you!
\n<br/>From C2k8pro with love
"""
subject ='[BirthReminder] Happy birthday to you! from C2k8pro'
send_mail(recipient, subject, body)
def send_notification(all_mails, names):
body = """Tomorrow is birthday of %s""" % names
send_mail(all_mails, body, body)
def test_send_mail():
notify_body = """Tomorrow is birthday of """
recipients = ['MYBOT#gmail.com']
today = datetime.now()
format = "%d-%m-%Y"
print today
today_in_str = datetime.strftime(today, format)
def read_csv():
FILENAME = 'mails.csv'
reader = csv.reader(open(FILENAME, 'rt'), delimiter=',')
today = datetime.now()
one_day = timedelta(days=1)
tomorrow = today + one_day
all_mails = []
str_format = "%d/%m"
str_today = today.strftime(str_format)
str_tomorrow = tomorrow.strftime(str_format)
print 'Today is ', str_today
tomorrow_birth = []
for row in reader:
name = row[1].strip()
dob = row[2]
dmy = dob.split("/")
mail = row[3]
all_mails.append(mail)
#TODO fix dob with only 1 digit
birth_date = dmy[0] + "/" + dmy[1]
if str_today == birth_date:
print 'Happy birthday %s' % name
try:
send_happybirthday(mail)
except Exception, e:
print e
elif str_tomorrow == birth_date:
tomorrow_birth.append(name)
print "Tomorrow is %s's birthday" % name
# Remove empty string
all_mails = filter(None, all_mails)
print 'All mails: ', len(all_mails)
str_all_mails = ', '.join(all_mails)
if tomorrow_birth:
all_tomorrow = ', '.join(tomorrow_birth)
send_notification(str_all_mails, all_tomorrow)
def main():
read_csv()
if __name__ == "__main__":
main()
Can anyone explain this. Thanks!
I found solution from here
Send Email to multiple recipients from .txt file with Python smtplib
I passed a string contain all recipients separated by comma to msg['To'] and sendmail().
It's true for msg['To'] but with sendmail, I have to use a list.

First python screen scraping and smtp script won't evaluate properly

Here's my script with the personal bits scrubbed.
import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp3 = opener.open('https://www.mynexia.com/login')
resp4 = resp3.read().split('input name=\"authenticity_token\" type=\"hidden\" value=\"')
resp5 = resp4[1].split('\" /></div>')
login = 'website username'
password = 'website pass'
authenticity_token = resp5
login_data = urllib.urlencode({'login' : login, 'password' : password,'authenticity_token' : authenticity_token})
opener.open('https://www.mynexia.com/session', login_data)
resp = opener.open('https://www.mynexia.com/houses/ourstaticaccountpage/climate')
resp1 = resp.read().split('<div class=\"temperature\"><span>')
resp2 = resp1[1].split('</span></div>')
int(resp2[0])
if resp2[0] > 75:
import smtplib
import string
SUBJECT = "Temperature is rising!"
TO = "helpdesk#whoever.blah"
FROM = "me#gmail.com"
text = "Temperature is " + resp2[0]
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("me#gmail.com", "gmailpass")
server.sendmail(FROM, [TO], BODY)
elif resp2[0] <= 75:
import smtplib
import string
SUBJECT = "Temperature is ok"
TO = "helpdesk#whereever.blah"
FROM = "me#gmail.com"
text = "Temperature is " + resp2[0]
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("me#gmail.com", "gmailpass")
server.sendmail(FROM, [TO], BODY)
It works fine, except it always evaluates resp2[0] as > 75 no matter what its value is. The point of this script is to alert me when a room that some sensitive machines are running in gets warmer than 75 degrees. The website I'm scraping from only allows you to send alerts if it gets over 90. By then I'm at risk of machines going down, so I wanted to alert myself earlier. I'm going to run it with a cronjob every 15 minutes, and once I get the if-else statement working right, I'm just going to have <= dump to a log file instead of sending out an "Everything is a-ok alert." Any suggestions on why I fail at basic math? Is there a problem with my int(resp2[0])? Is it not base 10 by default?
resp2 is a list of strings. A string is greater than an integer. You need to call int on it before comparison.
Actually, I see that you are calling int - but you're not doing anything with the result. Doing int(resp2[0]) doesn't convert the contents of resp2[0] to an integer. It simply returns the converted value. If you don't assign it to anything, it just gets thrown away. You need to assign it to a new variable, and then use that variable in your if statements.
Have you tried logging the value of resp2[0] to see what values you are getting? A simple
print resp2[0]
while debugging...

Categories