Blocked by Spamhaus When Trying to Validate Email Using Python - python

I'm trying to check whether an email exists or not using Python's smtplib
This is what I did:
s = smtplib.SMTP()
s.connect(mxRecord)
s.mail('my#email.com') //Here the error shows up
The error is:
Client host [...] blocked using Spamhaus. To request removal from this list see http://www.spamhaus.org/lookup.lasso (S3130)

I tried something and it worked well.
import dns.resolver, smtplib
MyEmail = "X#hotmail.com"
MyPassword = "XXX"
EmailToValidate = "X#Y.com"
record = dns.resolver.query(str.split(EmailToValidate, "#")[1], "MX")
mx = str(record[0].exchange)
server = smtplib.SMTP("smtp.live.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(MyEmail, MyPassword)
server.helo("live.com")
server.connect(mx)
server.mail(MyEmail)
code, msg = server.rcpt(EmailToValidate)
print("Code: ", str(code), " message: ", msg)
the (code, message) pair will be (250, OK) if the email exists, and (550, Address Rejected) if the email does not exists.
I wrote this on hurry, so there might be some unnecessary steps.

Related

Sending email using Python with smtp

I am trying to write a module as part of my code to send out email. I have this code down which does not throw any exception but it does not deliver email as I expect. Can anyone help me point out any issue this code might have? Thanks in advance!
""" before sending email with this code
I start smtp server:
python -m smtpd -n -c DebuggingServer localhost:1025
"""
#!/usr/bin/python -tt
from email.mime.text import MIMEText
from datetime import date
import smtplib
SMTP_SERVER = "localhost"
SMTP_PORT = 1025
EMAIL_TO = ["user385#dispostable.com"]
EMAIL_FROM = "user383#testdomain.com"
EMAIL_SUBJECT = "*Email Test*"
DATE_FORMAT = "%d/%m/%Y"
EMAIL_SPACE = ", "
DATA='Test email sending feature in Python'
def send_email():
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + " %s" %(date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__=='__main__':
try:
send_email()
except Exception as e:
import traceback;traceback.print_exc()
Thanks
hi can you remove the try except and run it again?
since youre using a gmail. can you try this one
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("user383#gmail.com", "your-password-here")
msg = "YOUR MESSAGE!"
server.sendmail("user383#gmail.com", "user385#dispostable.com", msg)
server.quit()

Connection Error SMTP python

I've been using python for a bit now and have been using the email function without any errors in the past but on the latest program I have made I've been getting this error
Traceback (most recent call last):
File "daemon.py", line 62, in <module>
scraper.run()
File "c:\cfsresd\scraper.py", line 48, in run
self.scrape()
File "c:\cfsresd\scraper.py", line 44, in scrape
handler(msg)
File "daemon.py", line 57, in handler
server.ehlo()
File "C:\Python27\lib\smtplib.py", line 385, in ehlo
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File "C:\Python27\lib\smtplib.py", line 318, in putcmd
self.send(str)
File "C:\Python27\lib\smtplib.py", line 310, in send
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
I used the same email code for all my projects but this is first time is done it. I've tried adding the connect() but that made no difference. Below is email section of my script
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
msg['Subject'] = "msg.channel"
msg['From'] = ('removed')
msg['To'] = ('removed')
server.login('user','password')
server.sendmail(msg.get('From'),msg["To"],msg.as_string())
server.close()
server.ehlo()
server.quit()
print 'sent'
cheers for any help
shaggy
all sorted took a few idea and tried the code below
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
server = smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login('user','pass')
msg['Subject'] = "msg.channel"
msg['From'] = ('from')
msg['To'] = ('to')
server.sendmail(msg.get('From'),msg["To"],msg.as_string())
server.quit()
So i removed ehlo(), close() and port number. now i have to workout how to change the subject to msg.channel so it changes each time.
thanks all
Try using SMTP's empty constructor, then call connect(host, port):
server = smtplib.SMTP()
server.connect('smtp.gmail.com', '587')
server.ehlo()
server.starttls()
server.login(username, password)
You have an ehlo after close. That seems unlikely to ever succeed. Also, quit does close so you can probably just get rid of the ehlo and close calls near the end
You can still have an encrypted connection with the smtp server by using the SMTP_SSL class without needing the starttls call (shorter). You don't need to be calling the ehlo every time, that's done automatically when needed, and when connecting to the default port, don't have to supply one when creating instances SMTP* classes.
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
msg['To'] = ','.join(receivers)
msg['Subject'] = 'msg.channel'
msg['From'] = 'someone#somedomain.com'
Using SMTP with the starttls:
server = smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login('user', 'password')
server.sendmail(msg['From'], receivers, msg.as_string())
and now with the SMTP_SSL class
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login('user', 'password')
server.sendmail(msg['From'], receivers, msg.as_string())
and finally
server.quit()
For Pyhton 3.6.*
Note : In gmail it will work only if 2-Step verification is turned off.
Allow gmail to open via low secured app.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_addr = 'sender-email-id'
to_addr = 'receiver-email-id'
text = 'Hi Friend!!!'
username = 'sender-username'
password = 'password'
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'Test Mail'
msg.attach(MIMEText(text))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()
I'm the maintainer of yagmail, a package that should make it really easy to send an email.
import yagmail
yag = yagmail.SMTP('user','password')
yag.send(to = 'to#gmail.com', subject = 'msg.channel')
when yag leaves scope, it will auto-close.
I would also advise you to register in keyring once, so you'll never have to write the password in a script. Just run once:
yagmail.register('user', 'password')
You can then shorten it to this:
SMTP().send('to#gmail.com', 'msg.channel')
You can install it with pip or pip3 (for Python 3). You can also read more about it, with functionality as easily adding attachments, inline images/html, aliases etc.
I had a similar problem when I tried to send an e-mail from Celery (as a Docker container). I added env_file to the worker and beat containers in a docker compose file.
env_file: ./env/dev/.env
In that file I have an e-mail configuration.
EMAIL_HOST=smtp.gmail.com
EMAIL_HOST_USER=your_mail
EMAIL_HOST_PASSWORD=your_password
EMAIL_PORT=587
I solved this error just by removing this line:
server.quit()
raise SMTPServerDisconnected('please run connect() first')
if you had this error you my be want install this :
pip install django-smtp-ssl
this one to install smtp library and ssl protocol
its work perfecly for me

Trying to send email from python

i am new to python, when am trying to sending mail by using python my program is bellow
import smtplib
from smtplib import SMTP
sender = 'raju.ab#gmail.com'
receivers = ['sudeer.p#eunoia.in']
message = """ this message sending from python
for testing purpose
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(username,password)
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
when i execute it shows Error: unable to send mail message, how to send email in python please explain
What i have done in code :
1.Added a error object to get the error message
import smtplib
from smtplib import SMTP
try:
sender = 'xxx#gmail.com'
receivers = ['xxx.com']
message = """ this message sending from python
for testing purpose
"""
smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login('xxx','xxx')
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
print "Error: unable to send email"
If u ran this code u would see a error message like this stating that google is not allowing u to login via code
Things to change in gmail:
1.Login to gmail
2.Go to this link https://www.google.com/settings/security/lesssecureapps
3.Click enable then retry the code
Hopes it help :)
But there are security threats if u enable it
as is said here: How to send an email with Gmail as provider using Python?
This code works. But GMAIL wil warn you if you want to allow this script send the email or not. Sign in in your account, and accesss this URL: https://www.google.com/settings/security/lesssecureapps
import smtplib
gmail_user = "yourmail#gmail.com"
gmail_pwd = "mypassword"
FROM = 'yourmail#gmail.com'
TO = ['receiber#email.com'] #must be a list
SUBJECT = "Testing sending using gmail"
TEXT = "Testing sending mail using gmail servers"
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
#server = smtplib.SMTP(SERVER)
server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
#server.quit()
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"

Gmail SMTP rejecting my login

smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvuQ\n5.7.14 hjav3RshZ9XqmApuN6mVTPJ_3AZUJEkiniSxdgdVMrgEpKpUtHi8_oCjzuOA9pkhGMyTrs\n5.7.14 fuSX9EuvWudU00Q1KXZgY4rZ1I5ZEEDOqvVMl7bOQitwyb_sYdgPA3tJC7_xpUN1zDC6Ib\n5.7.14 MjA2mM_oMdCOeCpodh-13LwLFlyzmZALwg2uu522OxG0NH74B2hafBfT2F1XK0lXCz1hce\n5.7.14 3yugD0g> Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 bw2sm40059670pad.46 - gsmtp')
I am getting the above error from the below script. And yes I have verified that I am using my correct credentials. All I want to do is send an email from a script! Has anyone run into this issue before?
import smtplib
FROMADDR = "my.real.address#gmail.com"
LOGIN = FROMADDR
PASSWORD = "my.real.password"
TOADDRS = ["my.real.address#gmail.com"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
You have to enable 'Access for less secure apps' option in your Google account security section.
Try changing your code to:
server.ehlo()
server.starttls()
server.ehlo() # you are missing elho to establish communication with server
server.login(username, password)
# Full script
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from_address = 'you#gmail.com'
to_address = 'you80#gmail.com'
text = 'test message sent from Python'
username = '****'
password = '****'
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = 'Foo'
msg.attach(MIMEText(text))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(from_address, to_address, msg.as_string())
server.quit()
If you have not logged in using your browser since the error messages, you should also try that as if you had a number of unsuccessful logins you will have to enter a captcha,
The solution to this ended up being changing my gmail password. I never did figure out which special characters were throwing everything off, but I just generated a new password and had no problems with this after that.

Sending Verizon SMS message via Python and smtplib

I can make smtplib send to other email addresses, but for some reason it is not delivering to my phone.
import smtplib
msg = 'test'
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login("<username>","<password>")
server.sendmail(username, "<number>#vtext.com", msg)
server.quit()
The message sends successfully when the address is a gmail account, and sending a message to the phone using the native gmail interface works perfectly. What is different with SMS message numbers?
Note: using set_debuglevel() I can tell that smtplib believes the message to be successful, so I am fairly confident the discrepancy has something to do with the behavior of vtext numbers.
The email is being rejected because it doesn't look an email (there aren't any To From or Subject fields)
This works:
import smtplib
username = "account#gmail.com"
password = "password"
vtext = "1112223333#vtext.com"
message = "this is the message to be sent"
msg = """From: %s
To: %s
Subject: text-message
%s""" % (username, vtext, message)
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg)
server.quit()
The accepted answer didn't work for me with Python 3.3.3. I had to use MIMEText also:
import smtplib
from email.mime.text import MIMEText
username = "account#gmail.com"
password = "password"
vtext = "1112223333#vtext.com"
message = "this is the message to be sent"
msg = MIMEText("""From: %s
To: %s
Subject: text-message
%s""" % (username, vtext, message))
server = smtplib.SMTP('smtp.gmail.com',587)
# server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg.as_string())
server.quit()

Categories

Resources