Python sending email via Gmail failed - python

I am using this piece of code:
import smtplib
fromaddr = 'fromuser#gmail.com'
toaddrs = 'myemail#gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'
# Credentials (if needed)
username = 'myusername'
password = 'passwd'
# The actual mail send
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
I am receiving this error:
Traceback (most recent call last): File "C:/Python34/sendemail.py",
line 15, in
server.starttls() File "C:\Python34\lib\smtplib.py", line 673, in starttls
raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.
When I do exculde server.starttls() I am receiving different error message about authentication. I have another price of code when I am accessing Gmail via web browser using webdriver and credentials works, so I copied and pasted to this code to make sure that credentials are correct.
I can't figure out why this is not working.
Thanks in advance.

you'll have to see here as well
use port 587
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()

Sending via Gmail works for me when using this code. Note that I use smtplib.SMTP() as opposed to smtplib.SMTP_SSL('smtp.gmail.com',465). Also try to use port 587 and not 465.
server = smtplib.SMTP()
server.connect(server, port)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(send_from, send_to, msg)
server.close()
Though I do find that using the emails library is much easier.

Please, try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.

It's either you use smtplib.SMTP() then starttls() (which I don't recommend), or you use smtplib.SMTP_SSL() alone ( dont't use starttls() after that)

Related

Can't send email (gmail) via python

I have a code which was working like a half year ago. It basiclly sends email.
import smtplib
import socket
gmail_user="SENDERMAIL"
gmail_password="SENDERPASS"
to = 'SENDTOTHIS'
email_text = "ADSADSADSA"
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.starttls()
server.sendmail(gmail_user, to, email_text)
server.close()
#I was using this code below and it was working. I tried above code but it also did not work.
#server = smtplib.SMTP("smtp.gmail.com:587")
#server.ehlo()
#server.starttls()
#server.ehlo()
#server.login(gmail_user, gmail_password)
#server.sendmail(gmail_user, to, email_text)
#server.close()
print("Done")
except Exception as exception:
print(exception)
Here's exception
(534, b'5.7.14
5.7.14 KL7_2qGSLW9IBjP8dKKgP67bEgyKNc5ls76dnVDZcUlVQjJUQb0JX9BIVi_Agb84vKNOKB
5.7.14 fshB0ngZ_Tn8ocDpDHKavRKXmluVjHo5YM7ADKENtWn4aVTxyvaBlbXRGpA1EBh91bdV-o
5.7.14 pwiAWUHXKmRQEuSNSiFcv68DP4a7ghIu9YKnTyqtUEhGd4HgKtxa4Jz0mhSQDjD13UQWYB
5.7.14 -YEL5Sd2h5YxN8kkSAsK-J_hXMbpy7wNyeCov8lq1Aa3spZzgo> Please log in via
5.7.14 your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/answer/78754 f132-v6sm3660398wme.24 - gsmtp')
I did try to
logined gmail
add device to trusted devices
turned on IMAP via gmail
let less secure apps
tried this:
https://support.google.com/mail/answer/7126229?visit_id=636711453029417344-336837064&rd=2#cantsignin
There are to many ways to solve this problem. I hope this code helps.
The only thing you need to do is filling the required variables.
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#
message = "Your message" # Type your message
msg = MIMEMultipart()
password = "********" # Type your password
msg['From'] = "from#gmail.com" # Type your own gmail address
msg['To'] = "To#gmail.com" # Type your friend's mail address
msg['Subject'] = "title" # Type the subject of your message
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
I can also advise to use a simpler library (a wrapper on top of smtplib, to make sure there are no other factors involved).... like yagmail (disclaimer: I'm the developer).
Try to see if this works:
import yagmail
yag = yagmail.SMTP("username", "password")
yag.send(subject="hi")

Python3 Sending Email with Smtplib [Yandex]

I'm trying to send emails using yandex but my function doesn't work. It's just waiting forever there is no error either. Here is my function :
def send_emails(title,msg):
server = smtplib.SMTP('smtp.yandex.com.tr:465')
server.ehlo()
server.starttls()
server.login(yandex_mail,yandex_pass)
message = 'Subject: {}\n\n{}'.format(title,msg)
server.sendmail(yandex_mail,send_to_email,message)
server.quit()
print('E-mails successfully sent!')
send_emails('Test Mail', 'Yes its a test mail!')
i think your problem is here:
server = smtplib.SMTP('smtp.yandex.com.tr:465')
you need to use smtplib.SMTP_SSL because connection is security with SSL docs, also smtplib.SMTP_SSL get many params, first is host and second is port and other params, but you need now only this two, you need to give host and port separately, try this
def send_emails(title,msg):
server = smtplib.SMTP_SSL('smtp.yandex.com.tr', 465)
...

Sending reports from my python script using gmail smtp

I'm trying to send email to myself with all reports collect each day from my scripts and below is the code I'm using to send the email.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
def send_email(message="", subject="EReport of Twitter Bot"):
msg = MIMEText(message)
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = subject
msg['From'] = 'r****#gmail.com'
msg['To'] = 'r****#gmail.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
try:
s = smtplib.SMTP('smtp.gmail.com',465)
s.ehlo()
s.starttls()
s.ehlo()
s.login('r****#gmail.com', 'mypassword')
s.sendmail('r****#gmail.com', 'r****#gmail.com', msg.as_string())
s.quit()
return True
except Exception as e:
print e
return False
if __name__ == "__main__":
if send_email(message="Hello Ravi!"):
print "Successfully sent the mail"
else:
print "Sorry"
However, I get Connection unexpectedly closed when using the port 465. And If I use port 587 I get the following
(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvkf\n5.7.14 g4kEFJrti_fMva0wSRWGl4KfuNsFhQumLhgzMCUlPCQn2dvYdPCDr03l9luBP2XTwcnf_N\n5.7.14 BNsPV2jZhLOPjFOSYtGM16Wb6A1BlmLvMP1_mMHoeo4plSVNGio8EDCx_RMW7HcJdYcpx9\n5.7.14 T5SHwceKzRdpUXHxdL2icc0KAMDtb1dDLDr389N_s-tnSkylcN0bwctBA0tKF2k0AC6OsX\n5.7.14 jIcP7iV3ArV6PEB2ZXPCOI2gRPg0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 lq10sm97657764pab.36 - smtp')
Which basically means my server is not trust worthy, although reverse-dns on my server's ip returns valid rent-history.com
Does anyone know what I can do/try to fix this?
Port 465 is used for SSL, port 587 not.
You should use SMTP_SSL when you intend to use secure connection (port 465), and SMTP with port 587.
Also, I'd like to point out yagmail; I developed it.
You can just use:
import yagmail
yag = yagmail.SMTP('r****#gmail.com', 'pw') # or yagmail.SMTP_SSL for port 465
yag.send('r****#gmail.com', "EReport of Twitter Bot", message)
Furthermore, it makes it easy to:
write the script in a passwordless manner
adding files by filenames (and it will automatically attach it using the correct mimetype)
it automatically sends HTML emails and uses plain text fallback
Install using pip (works for both python 2 and 3):
pip install yagmail
You may need to log into whatever gmail account you are using and go to the less secure apps secion to enable access via a less secure app, such as your program. Obviously, this decreases the account's security, so I don't recommend you do this with a personal account.

Strange error in python using SMTPLIB module

still having issues. I just added some code which uses the smtplib module to send an email to the email address that has been entered by the user, however I got this error
File "C:\Python27\lib\smtplib.py", line 555, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
SMTPException: SMTP AUTH extension not supported by server.
The code I used was from a beginners website
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("youremailusername", "password")
msg = "\nHello!"
server.sendmail("you#gmail.com", "target#example.com", msg)
However in my case, I used the name of a variable which holds the email or the user where it says "target #example.com" Help someone? ALso I would like to know what are the numbers that come after "smtp.gmail.com"? The 587?
you need to add this server.starttls() before login
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("youremailusername", "password")
msg = "\nHello!"
server.sendmail("you#gmail.com", "target#example.com", msg)
starttls put the SMTP connection in TLS (Transport Layer security)

send email using SMTP SSL/Port 465

I need to send email using SMTP SSL/Port 465 with my bluehost email.I can't find working code in google i try more than 5 codes. So, please any have working code for sending email using SMTP SSL/port 465 ?
Jut to clarify the solution from dave here is how i got mine to work with my SSL server (i'm not using gmail but still same). Mine emails if a specific file is not there (for internal purposes, that is a bad thing)
import smtplib
import os.path
from email.mime.text import MIMEText
if (os.path.isfile("filename")):
print "file exists, all went well"
else:
print "file not exists, emailing"
msg = MIMEText("WARNING, FILE DOES NOT EXISTS, THAT MEANS UPDATES MAY DID NOT HAVE BEEN RUN")
msg['Subject'] = "WARNING WARNING ON FIRE FIRE FIRE!"
#put your host and port here
s = smtplib.SMTP_SSL('host:port')
s.login('email','serverpassword')
s.sendmail('from','to', msg.as_string())
s.quit()
print "done"
For SSL port 465, you need to use SMTP_SSL, rather than just SMTP.
See here for more info.
https://docs.python.org/2/library/smtplib.html
You should never post a question like this. Please let us know what you have done, any tries? Any written code etc.
Anyways I hope this helps
import smtplib
fromaddr = 'uremail#gmail.com'
toaddrs = 'toaddress#ymail.com'
msg = "I was bored!"
# Credentials
password = 'password'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(fromaddr,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print "done"

Categories