I am formatting Python code using pylint and getting some unwanted warning messages which are given below.
C:204, 0: Invalid function name "sendPasswordViaEmail" (invalid-name)
C:207, 4: Invalid variable name "to" (invalid-name)
W:213, 4: Statement seems to have no effect (pointless-statement)
I am providing my code related to the above messages below.
if request.method == 'POST':
name = request.POST.get('uname')
email = request.POST.get('uemail')
range_start = 10 ** (4 - 1)
range_end = (10 ** 4) - 1
password = randint(range_start, range_end)
passw = User(
uname=name,
password=password,
raw_password=password,
)
passw.save()
sendPasswordViaEmail(str(password), email)
return render(request, 'bookingservice/login.html')
def sendPasswordViaEmail(password, email):
""" Send email to user"""
to = email
gmail_user = settings.EMAIL
gmail_pwd = settings.PASSWORD
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + \
gmail_user + '\n' + 'Subject:password \n'
msg = header + '\n Your password is\n\n' + password
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
These messages are warnings (your code works), not errors.
sendPasswordViaEmail is a camel case name. Functions should be "snake case". Rename it send_password_via_email.
to is too short. Try recipient or something else meaningful in place.
The line containing smtpserver.ehlo whithout parentheses does nothing and is thus useless.
Related
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 :-)
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
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
This program works quite well except for when dealing with logging in with Gmail. I wasn't quite sure if this was a problem with Gmail specifically, or a problem with my program. Comcast, AOL, and Yahoo! work fine.
import socket
import smtplib
email_provider = raw_input('Gmail, AOL, Yahoo! or Comcast? ').title()
email_user = raw_input('Type in your full email username. ')
email_pwd = raw_input('Type in your email password. ')
if email_provider == 'Gmail' or 'Google':
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
if email_provider == 'Aol' or 'AOL':
smtpserver = smtplib.SMTP("smtp.aol.com",587)
if email_provider == 'Yahoo' or 'Yahoo!':
smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",587)
if email_provider == 'Comcast' or 'Xfinity':
smtpserver = smtplib.SMTP("smtp.comcast.net",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(email_user, email_pwd)
sendto = raw_input('Email address to send message to: ')
to = sendto
CC = sendto
subj = raw_input('Subject: ')
header = 'To: ' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject:' + subj +'\n'
print '\nMessage Details:'
print (header)
assignment=raw_input('Enter your message: ')
msg = header + assignment + '\n'
smtpserver.sendmail(email_user, to, msg)
print ('Your message has been sent!')
smtpserver.close()
This is a problem:
if email_provider == 'Gmail' or 'Google':
Python works on truthy values. Anything that isn't False, None, 0 or an empty collection/mapping will be True.
From what it looks like, the execution chain will fall all the way through until it sets your SMTP connection credentials to Comcast's server.
So, effectively, your first statement is saying this:
if email_provider == 'Gmail' or True
You would want to change it to this:
if email_provider in ('Gmail', 'Google')
Then, realistically, those could be rewritten as elif - only one of those statements are going to be true at any given time.
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.