I'm getting a "aborted (disconnected)" when sending multiple emails with smtplib (python 3.6) and I can't find much information online. I'm pretty sure the error is coming from the server and not my code but I'd like to know how to fix this or at least get a clue of what to google to get more information because I am clueless as to how I am going to fix this.
This is the function I'm using the send one e-mail: ( I am calling this function five times and I'm getting the error ).
import smtplib
def enviar_um_mail(to, subject, body):
#source: https://stackabuse.com/how-to-send-emails-with-gmail-using-python/
user = '<mail here>'
password = '<passwrd here>'
sent_from = user
to = 'somemail#somedomain.org'
email_text = 'text of e-mail here'
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(user, password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('Email sent!')
except Exception as e:
print ('Something went wrong...')
print(e)
When calling this function five times the python shell shows:
Email sent!
Email sent!
Email sent!
Email sent!
Email sent!aborted (disconnected)
Related
I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but there is X delay between sending email from gmail server to school email and it potentially should be achieveable to cut it down slightly so I thought about python script to do it. I think I can get around sending it at a given time but struggle to actually send the message.
There are threads in stackoverflow suggesting python solution e.g.: How do I schedule an email to send at a certain time using cron and smtp, in python? but unfortunately it looks like gmail disabled the option to send mails from non-authorized apps.
Other threads suggest that enabling less secure apps is needed. Unfortunately, this setting has been closed by Google. What could be the way around it?
My sample code:
`
def send_mail():
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo() # optional
print('Server initialized')
sent_from = gmail_user
to = ['xxxxxxxx#gmail.com']
subject = 'my subject'
body = 'my body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server_ssl.sendmail(sent_from, to, email_text)
server_ssl.close()
except Exception as inst:
print('Something went wrong')
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst)
`
is returning an error:
<class 'smtplib.SMTPSenderRefused'> (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError
You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
print( 'waiting to login...')
server.login(sender_email, password)
print( 'waiting to send...')
server.sendmail(sender_email, receiver_email, text)
I have tested the below code with gmail credentials and it works perfectly, however, when I try to use an email created within a cPanel it does not work. I am certain that the credentials are correct and that I am not being blocked by the server as my email client is working and I can telnet to it.
Is there a way to somehow produce logs to see why exactly it's failing? Using print statements I found that it fails when it gets to the server variable.
import config
import smtplib
class EmailAlert(object):
"""Class for sending email alert from slave account"""
def __init__(self, subject, msg):
self.subject = subject
self.msg = msg
def send_email(self):
try:
server = smtplib.SMTP(config.OUTGOING_SERVER) #It fails here and goes to except
server.ehlo()
server.starttls()
server.login(config.FROM_EMAIL_ADDRESS, config.PASSWORD)
message = 'Subject: {}\n\n{}'.format(self.subject, self.msg)
server.sendmail(config.FROM_EMAIL_ADDRESS,
config.TO_EMAIL_ADDRESS,
message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
email = EmailAlert("Test", "test")
email.send_email()
I found that using port 587 works even though the port shown in cPanel's is usually 465.
#!/usr/bin/python
import smtplib
message = """From: Test <test#fromdomain.com>
To: test<test#todomain.com>
Subject: SMTP test
This is test
"""
try:
smtpObj = smtplib.LMTP('exhange.intranet',25)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Hello basiclly im testing open relay server and here is question is there other method to send mail without any authetication than LMTP ?How i can implement this with SMTP which paramter is that ?
Sending a mail with only smtp is getting blocked on exhange easyli, there must be included NOT authetication information for exhange to pass it through.
To use SMTP without authentication, use code like the following:
smtpObj = smtplib.SMTP('exhange.intranet',25)
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
I have a script that will be running nightly. I want it to send me an email when it fails to complete. I wrote a short test script to learn how to send an email with Python. In my IDE it runs without error messages but no email. I'm running from one of our servers (not the email server) which doesn't have any email restrictions.
I tried it in the Python shell so I can read any messages:
I tried sending to my gmail account and it get this error:
SMTPRecipientsRefused: {'blahblahblah#gmail.com': (550, '5.7.1 Unable to relay')}
Any ideas??
More info:
I modified the code found here to work with our email.
def send_email(user, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("workemailserver.com")
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
With this I can send an email to my coworkers, but not myself. No biggie because I can use a coworkers email as the sender. Our "email server" relays the messages to office365, so that's why I cant send to my gmail.
My problem is basically solved. But I was never able to get the "simpler" code on top to work when I had tried sending to coworkers?
SMTPRecipientsRefused: (550, '5.7.1 Unable to relay')
This means the server you used can not relay the message to the target recipient. This usually happens when your email server has configuration issues.
import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP('smtp.gmail.com', 465)
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except SMTPException:
print("Error: unable to send email")
I've created two new email accounts (above), both on the same server (gmail) to test this.
It reaches the point in which it prints "trying host and port..." and does not go any further. So the problem should be with the address and port number I entered. But according to gmail's outgoing mail server details i've inputted them correctly. Any ideas what's wrong?
If I remove the port number or try a different port number such as 587 i'm provided with an error.
Sending email via Gmail's SMTP servers requires TLS and authentication. To authenticate, you will need to make an application-specific password for your account.
This script worked for me (though I used my own GMail email address and my own application-specific password). In the code below, replace APPLICATION_SPECIFIC_PASSWORD with the password you generated.
import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("den.callanan#gmail.com", "APPLICATION_SPECIFIC_PASSWORD")
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")
import traceback
traceback.print_exc()
(To debug the problem, I added the print-traceback code in the except statement. The exceptions had specific information on how to get it to work. The code hung when accessing port 465, I think because of problems with TLS negotiation, so I had to try using port 587; then I got good debugging info that explained what to do.)
You can see info on the SMTP_SSL object here.