Python smtplib hangs when sendmessage() is called - python

I'm trying to send a message from a gmail account using smtplib. I've been messing with it in the shell, and everything works fine until I call sendmail(), when it just freezes until I close the terminal. No errors, just freezing. My commands look like this:
>>> import smtplib
>>> connection = smtplib.SMTP("smtp.gmail.com", 587)
>>> connection.ehlo()
>>> connection.starttls()
>>> connection.login("gmail_id", "gmail_pwd")
>>> connection.sendmail("addr_from", "addr_to", "message")
Has anybody had this problem? I've tried pinging smtp.gmail.com and using telnet smtp.gmail.com 587, and they both connect.

Use connection.set_debuglevel(1) to enable tracking/debugging SMTP session.
https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.set_debuglevel

I had a similar issue just now, I had tried to login to my gmail account using python3.7's smtplib and was getting:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials')
I went to my gmail inbox using a browser, saw that I received a security alert email with the message
Less secure app blocked: Google blocked the app you were trying to use
because it doesn't meet our security standards.Some apps and devices
use less secure sign-in technology, which makes your account more
vulnerable. You can turn off access for these apps, which we
recommend, or turn on access if you want to use them despite the
risks. Google will automatically turn this setting OFF if it's not
being used.
After I followed the instructions in the aforementioned email and enabled less secure apps access on my gmail account, I tried sendmail still using the initial SMTP connection, but it just hung with no output.
I then proceeded to quit the initial SMTP connection and created a new one (post less secure apps enabled) like below and it worked!
conn = smtplib.SMTP('smtp.gmail.com', 587)

Related

Sending mail with python SMTP to outlook/microsoft gives SMTPAuthenticationError: Authentication unsuccessful

I have a problem described and solved for gmail in this post. I have read through several posts dealing with similar issues (Sending mail from Python using SMTP, Sending email from Python using STARTTLS, smtplib.SMTPAuthenticationError: (535, '5.7.3 Authentication unsuccessful')) and also some external support on Microsoft (eg. send email using Microsoft 365 but in none I was able to figure out how to fix my error.
My code is this:
import getpass
import smtplib
mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
a = getpass.getpass('Password: ')
mailserver.login('name#domain.com', a)
and connection is established (ie. I get 250 for .ehlo and 220 for .starttls) but the last step gives me:
SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [LO4P123CA0352.GBRP123.PROD.OUTLOOK.COM]')
The documentation says:
SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.
I am sure that my password and username are correct (triple checked that). Also, I looked to my account and in the Microsoft account it shows that POP and IMAP are allowed and it gives me:
Server name: smtp.office365.com
Port: 587
Encryption method: STARTTLS
so everything should be ok. I have also tried port 25 which gives the same error. Where is the problem? How can I make it work for Outlook/Microsoft 365? Thanks for any help.

Unable to connect to gmail/Outlook using IMAP in python

I have tried to connect to the Gmail server using IMAP in Spyder(Python 3.6) using the Chilkat package.
I have enabled the IMAP for all Mail in the Settings>Forwarding and POP/IMAP and then I have also enabled the less secure apps tab here https://myaccount.google.com/lesssecureapps?pli=1 after signing in. But in this code
import sys
import chilkat
imap = chilkat.CkImap()
# Anything unlocks the component and begins a fully-functional 30-day trial.
success = imap.UnlockComponent("Anything for 30-day trial")
if (success != True):
print(imap.lastErrorText())
sys.exit()
# Connect to an IMAP server.
# Use TLS
imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.gmail.com")
The success variable which is a boolean remains False. Please help me. My aim is to fetch all attachments from Outlook Server and dump them into a file.But I cannot even connect to the Gmail server. I tried to use "imap.mail.Outlook.com" but that also failed. I do not know the steps to enable IMAP in Outlook. But even if it is enabled in Gmail, why is it not working?
The 1st step is to examine the contents of the imap.LastErrorText property to see what happened. For example:
# Connect to an IMAP server.
# Use TLS
imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.someMailServer.com")
if (success != True):
print(imap.lastErrorText())
sys.exit()
My guess is that a firewall (software or hardware) is blocking the outbound connection.
An alternative solution is to use the GMail REST API as shown in these examples: https://www.example-code.com/python/gmail.asp The HTTP ports (443) are unlikely to be blocked by a firewall. You would download into a Chilkat Email object and then save attachments in exactly the same way had you downloaded via IMAP.

Send email from python webapp2 Google App Engine

i am trying to send an email from my application. The code run successfully with out error. But it do not send the email. It show this message on Console.
You are not currently sending out real email.
If you have sendmail installed you can use it by using the
server with --enable_sendmail
The sample code provided by the google is:
message = mail.EmailMessage(
sender="shaizi9687#gmail.com",
subject="Your account has been approved")
message.to = "ABC <shahzebakram#hotmail.com>"
message.body = """Dear Albert:
Your example.com account has been approved. You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.
Please let us know if you have any questions.
The example.com Team
"""
message.send()
That's because the dev_appserver by default doesn't send out real mails.
Email sending will work when you push to a live server, for eg:
appcfg update /path/to/app/
But like the error message points out, you'll have to use the --enable_sendmail flag if you have sendmail installed on your system or use smtp flags, for eg:
dev_appserver /path/to/app/ --enable_sendmail=yes
or another eg using gmail as smtp provider
dev_appserver /path/to/app --smtp_host=smtp.gmail.com --smtp_port=465 \
--smtp_user=user#gmail.com --smtp_password=password
More explanation here: https://cloud.google.com/appengine/docs/python/mail/
Mail and the development server
The development server can be configured to send email messages
directly from your computer when you test a feature of your app that
sends messages. You can configure the development server to use an
SMTP server of your choice. Alternatively, you can tell the
development server to use Sendmail, if Sendmail is installed on your
computer and set up for sending email.
If you do not configure an SMTP server or enable Sendmail, when your
app calls the Mail service, the development server will log the
contents of the message. The message will not actually be sent.

Using Gmail Through Python Authentication Error

*EDIT: SOLVED IT (answer below)
I'm getting an authentication error 534 from gmail when I try to run the following code:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("me#gmail.com", "password")
msg = "Hello from the other side!"
server.sendmail("me#gmail.com", "me#gmail.com", msg)
server.quit()
return 'Message Sent'
I also noticed that google picked up the login attempt and flagged it as a suspicious device because I'm runnning the code from a server on AWS in another state... however, I flagged it as my device, and I'm still getting the same error. What should I do?
*I also DID turn on access for less secure apps to login.
After telling google that it WAS my device, I just had to do this before the changes could propagate!
https://accounts.google.com/DisplayUnlockCaptcha
Problem = Solved

Sending an email, via python, from one outlook account to another

I'm writing a program to help the school's Biology Department and it involves sending an email. I've gathered all of the variables I need for the content of the message, it's just the actual sending of the email that's causing some issues.
I've looked around and realized that I was using code that sent to gmail, whereas the servers at school use Outlook 2010. Once I remembered that, I looked around for some python code that sent emails, but so far nothing has worked.
It all seems very complicated for just sending an email, but I need some help as to were to go from here.
gsal.org.uk is our school's web server address, which is an outlook server.
The current error that I am receiving is smtplib.SMTPException: STARTTLS extension not supported by server., but I keep receiving various errors with everything I try.
This is the code:
fromaddr = "test#gsal.org.uk"
toaddrs = "technicians#gsal.org.uk"
msg = "\r\n".join([
"From: user",
"To: user",
"Subject: Practical Request",
"",
"Test"
])
server = smtplib.SMTP_SSL('smtp.gmail.com:465')
server.ehlo()
server.starttls()
# server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
messagebox.showinfo("Success!", "Your request has been sent successfully.")
All I want to do is send an email from an email account (specified within the program) to an email account that will soon be set up at school called technicians#gsal.org.uk. Any help appreciated.
EDIT
Thought I'd add the fact that if I remove the starttls() line, I get this:
smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/answer/14257 hw1sm42144009wjb.6 - gsmtp', 'test#gsal.org.uk')
I've read that link, but it seems to be talking about gmail? I want to use outlook? I understand that I need to do authentication, but how?
In order to fight spam and protect resources, a normally configured SMTP server provides its services only to its owner (e.g. a company, organization or registered customers). Your school server probably accepts mail only if it is:
addressed to the school's own domain, or
coming from an authenticated person (e.g. a student, teacher), or
coming from a host with IP address belonging to the school's LAN (when allowed by the admin)
Further, a SMTP server communicates with other servers on TCP port 25 and with users submitting new mail (which is your case) on port 465 or 587. (Port 25 was used in the past for all mail, this is now deprecated)
Communication on port 465 is always encrypted (TLS). Communication on port 587 starts in plaintext, but with the STARTTLS command, the encryption is turned on. A successfull STARTTLS is usually required to allow authentication (login).
Why your progam does not work?
You are trying to start TLS on an TLS connection. It has been started. Either don't STARTTLS or change the port to 587.
You are using gmail's server to send a message not addressed to gmail. In this case you must login with a name and a password as a registered gmail user.
What should help? Contact the local admin for details about using the school's own server.

Categories

Resources