NameError: name 'mail' is not defined - python

i am very new to programming, i am supposed to count the number of unread eamails in my inbos usiong python. i am getting a name error saying that "mail" is not defined. i am not sure about the logic either. Here is the code:
import imaplib
<!-- begin snippet: js hide: false console: true babel: false -->
import datetime
import email
import getpass
def readmail():
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mypassword = getpass.getpass("Password: ")
address = '#mail.com'
mail.login(address, mypassword)
now = datetime.date.today()
mail.select("inbox")
print("Checking for new e-mails for ", address, ".")
typ, messageIDs = mail.search(now, "UNSEEN")
messageIDsString = str(messageIDs[0], encoding='utf8')
listOfSplitStrings = messageIDsString.split(" ")
print (len(listOfSplitStrings))

Fix code indentation
import imaplib
import datetime
import email
import getpass
def readmail():
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mypassword = getpass.getpass("Password: ")
address = '#mail.com'
mail.login(address, mypassword)
now = datetime.date.today()
mail.select("inbox")
print("Checking for new e-mails for ", address, ".")
typ, messageIDs = mail.search(now, "UNSEEN")
messageIDsString = str(messageIDs[0], encoding='utf8')
listOfSplitStrings = messageIDsString.split(" ")
print (len(listOfSplitStrings))
if __name__=="__main__":
readmail()

Related

how to resolve' NameError: name 'imaplib' is not defined' (python poetry)

I spend a lot of time resolving this problem but I couldn't,
So I want someone to help me.
I'm beginner for python and use poetry.
When I import imaplib I always get an error.
' NameError: name 'imaplib' is not defined'
I know I don't need to install imaplib'.
what should I do then?
This below is my code.
Thank you for your reading and kindness.
I appreciate it.
import imaplib
import email
host = 'imap.gmail.com'
username = 'xxxxxxx#gmail.com'
password = 'xxxxxxxx'
mail = imaplib.IMAP4_SSL(host)
mail.login(username, password)
mail.select('inbox')
_, search_data = mail.search(None, 'UNSEEN')
for num in search_data[0].split():
# print(num)
_, data = mail.fetch(num, '(RFC822)')
# print(data[0])
_, b = data[0]
email_message = email.message_from_bytes(b)
#email_message = email.message_from_string(b)
# print(email_message)
for part in email_message.walk():
if part.get_content_type() == 'text/plain' or part.get_content_type() == 'text/html':
body = part.get_payload(decode=True)
print(body)
print(search_data)

name 'search' is not defined In Sublime Texte 3 (search of IMAP)

i want to downloap PJ from an email so i write this code
import imaplib, email, os
from time import sleep
user='my_email'
password = 'secret'
imap_url = 'Outlook.office365.com'
con = imaplib.IMAP4_SSL(imap_url)
con.login(user,password)
def get_attachments(msg):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath,'wb') as f:
f.write(part.get_payload(decode=True))
attachment_dir = "D:/TOUT/DATANALYSE/email_python/attachement/"
never_stop = True
while never_stop:
last_email_id = search('FROM', "kvaccarin#datanalyse.fr", con)[0].split()[-1]
typ, data = con.fetch(last_email_id, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
get_attachments(msg)
time.sleep(12*60*60)
this code works when i run on Jupyter but when i want to run this code with Sublime Texte i have this error:
NameError: name 'search' is not defined
This fonction search() is not the fonction from re but it's the fonction from IMAP
Someone know how to fix it?
It's the beginning of the answers... but it's something!
Thanks to Max, I understand the error on the first Question, So to fix it I define a new function search_data():
def search_data(key,value,con):
result, data = con.search(None,key,'"{}"'.format(value))
return data
and when I run the same code with the use of this function like that:
import imaplib, email, os
from time import sleep
user='my_email'
password = 'secret'
imap_url = 'Outlook.office365.com'
con = imaplib.IMAP4_SSL(imap_url)
con.login(user,password)
def get_attachments(msg):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath,'wb') as f:
f.write(part.get_payload(decode=True))
def search_data(key,value,con):
result, data = con.search(None,key,'"{}"'.format(value))
return data
attachment_dir = "D:/TOUT/DATANALYSE/email_python/attachement/"
never_stop = True
while never_stop:
last_email_id = search_data('FROM', "kvaccarin#datanalyse.fr", con)[0].split()[-1]
typ, data = con.fetch(last_email_id, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
get_attachments(msg)
time.sleep(12*60*60)
there still have an error:
error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
I know it's the beginning of the answer but it perhaps helps to have the entire answer!

Email is not being sent via python

I have created this piece of code as a test run to send an email over python:
import smtplib
import random
import math
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
ADMIN_EMAIL = email
ADMIN_PASS = password
def generate_ver_code():
digs = "0123456789"
code = ""
for i in range(0, 6):
code += digs[math.floor(random.random() * 10)]
return code
def signup(forename, surname, email, occupation, dob, pass1, pass2, pass_match):
ran_num = str(random.randint(0, 9999))
if len(ran_num) >= 4:
if len(ran_num) == 1:
ran_num = "000" + str(ran_num)
elif len(ran_num) == 2:
ran_num = "00" + str(ran_num)
elif len(ran_num) == 3:
ran_num = "0" + str(ran_num)
elif len(ran_num) == 4:
ver_code = str(ran_num)
username = ran_num + forename[:3] + surname[:3] + dob[:2]
if pass1 == pass2:
passw = pass1
pass_match = True
else:
pass_match = False
s = smtplib.SMTP('smtp.gmail.com', 5354)
#home port = 5354
#school port =
s.starttls()
s.login(ADMIN_EMAIL, ADMIN_PASS)
msg = MIMEMultipart()
message = message_template.substitute(PERSON_NAME=forename)
msg['From']=ADMIN_EMAIL
msg['To']=email
msg['Subject']="Verify account: FAKtory Reset"
msg.attach(MIMEText(message, '\nBefore you can continue to use your account please verify yur account and check if the credentials are correct:\nUsername: '+ username + '\nName: ' + forename + ' ' + surname + '\nOccupation: ' + occupation + '\nDoB: ' + dob + '\nPassword: ' + pass1 + '\nVerification Code: ' + ver_code + '\nIf any of the credentials are wrong please enter them again on our app.\nThank you,\nRegards,\nFaizan Ali Khan\nAdmin'))
s.send_message(msg)
del msg
pass_match = False
forename = str(input("Enter your forename: "))
surname = str(input("Enter your surname: "))
email = str(input("Enter your email: "))
occupation = str(input("Enter your occupation: "))
dob = str(input("Enter your date of birth (DD/MM/YYYY): "))
pass1 = str(input("Enter your password: "))
pass2 = str(input("Enter your password again: "))
print(signup(forename, surname, email, occupation, dob, pass1, pass2, pass_match))
Now whenever I run the code it goes fine for the inputs but when it comes to sending the email I get this error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
How would you fix this error? I tried changing the port but still it doesn't work.
s = smtplib.SMTP('smtp.gmail.com', 5354)
The issue is this code snippet. According to the official Gmail IMAP Guide the outgoing port is either 465 or 587:
The outgoing SMTP server, smtp.gmail.com, requires TLS. Use port 465, or port 587 if your client begins with plain text before issuing the STARTTLS command.

Line breaks in SMTPLIB Python 3

I am trying to make a script that sends a email. But how to do line breaks? I tried the following:
Change msg = MIMEText(msginp) to msg=MIMEText(msginp,_subtype='plain',_charset='windows-1255')
NOTE: msginp is a input (msginp = input('Body? '))
Does anybody know how to make line breaks? Like the enter key on your keyboard?
My code is:
import smtplib
from email.mime.text import MIMEText
import getpass
smtpserverinp = input('What SMTP server are you using? (Look here for more information. https://sites.google.com/view/smtpserver) ')
usern = input('What is your email adderess? ')
p = getpass.getpass(prompt='What is your password? (You will not see that you are typing because it is a password) ')
subjectss = input('Subject? ')
msginp = input('Body? ')
toaddr = input('To who do you want to send it to? ')
msg = MIMEText(msginp)
msg['Subject'] = subjectss
msg['From'] = usern
msg['To'] = toaddr
s = smtplib.SMTP(smtpserverinp, 587)
s.starttls()
s.login(usern, p)
s.sendmail(usern, toaddr, msg.as_string())
s.quit()
Thanks!
I can't add a comment to see if this was totally what you want but i'll give it ago.
Your msginp = input('Body? ') ends once you press the enter key, for a new line you'd need to enter \n. Rather than typing \n each time you can make a loop.
Once all the data has been collected you can use the MIMEText as you would before.
Replace your msginp and MIMEText with this (total is the msginp)
total = ""
temp = input("Data: ")
total = temp+"\n"
while(temp!=""):
temp = input("next line: ")
total = total+temp+"\n"
msg = MIMEText(total)
Exit when you enter empty line
print("Body? ", end="")
lines = []
while True:
line = input("")
if not len(line):
break
lines.append(line)
print("\n".join(lines))

Python Error while using Google Apps Engine

I am hosting a website on Google Apps Engine and am trying to use Python's mail API to take POST data and send an email.
Here is my script:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
class SendEmail(webapp.RequestHandler):
def post(self):
name = self.request.get('name')
# self.response.out.write(name)
email = self.request.get('email')
tempSubject = self.request.get('subject')
msg = self.request.get('message')
if name is None:
self.response.out.write("Error: You did not enter a name.")
elif email is None:
self.response.out.write("Error: You did not enter an email.")
elif tempSubject is None:
self.response.out.write("Error: You did not enter a subject.")
elif msg is None:
self.response.out.write("Error: You did not enter a message.")
else:
_subject = "Msg from: " + name + "Re: " + tempSubject
message = mail.EmailMessage(sender = "foo#bar.com", to = "bar#foo.com", subject = _subject, body = msg, reply_to = email)
message.send()
def runApp():
application = webapp.WSGIApplication([('/email', SendEmail)], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
runApp()
And here is the traceback from the log on the server:
<type 'exceptions.NameError'>: name 'name' is not defined
Traceback (most recent call last):
File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 5, in <module>
class SendEmail(webapp.RequestHandler):
File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 14, in SendEmail
if name is None:
I ran the script locally with no errors, but once I try to run it on the server it keeps insisting the name variable I declared doesn't exist. Any idea why this happens?
Also, if I comment out that line, it says email doesn't exist, and so forth
As it turns out, sometimes I used spaces to indent and other times I used tabs. Python didn't like that. Here is the final code:
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
class SendEmail(webapp.RequestHandler):
def post(self):
name = self.request.get('name', '')
email = self.request.get('email', '')
tempSubject = self.request.get('subject', '')
msg = self.request.get('message', '')
if name is None:
self.response.out.write("Error: You did not enter a name.")
elif email is None:
self.response.out.write("Error: You did not enter an email.")
elif tempSubject is None:
self.response.out.write("Error: You did not enter a subject.")
elif msg is None:
self.response.out.write("Error: You did not enter a message.")
else:
_subject = "Message from: " + name + ", Re: " + tempSubject
msg += "\n\nI can be reached at "
msg += email
message = mail.EmailMessage(sender = "foo#bar.com", to = "bar#foo.com")
message.subject = _subject
message.body = msg
message.send()
self.redirect('/')
def runApp():
application = webapp.WSGIApplication([('/email', SendEmail)], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
runApp()

Categories

Resources