Can't send email (gmail) via python - 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")

Related

Getting error: SMTP AUTH extension not supported by server Python3

when I test below code with server = smtplib.SMTP('smpt.gmail.com:587') it works fine.
But when I change SMTP server to server = smtplib.SMTP('10.10.9.9: 25') - it gives me an error. This SMTP does not require any password.
So what am I missing here?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd
def send_email(user, recipient, subject):
try:
d = {'Col1':[1,2], 'Col2':[3,4]}
df=pd.DataFrame(d)
df_html = df.to_html()
dfPart = MIMEText(df_html,'html')
user = "myEmail#gmail.com"
#pwd = No need for password with this SMTP
subject = "Test subject"
recipients = "some_recipientk#blabla.com"
#Container
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = user
msg['To'] = ",".join(recipients)
msg.attach(dfPart)
#server = smtplib.SMTP('smpt.gmail.com:587') #this works
server = smtplib.SMTP('10.10.9.9: 25') #this doesn't work
server.starttls()
server.login(user, pwd)
server.sendmail(user, recipients, msg.as_string())
server.close()
print("Mail sent succesfully!")
except Exception as e:
print(str(e))
print("Failed to send email")
send_email(user,"","Test Subject")
IF the server does not require authentication THEN do not use SMTP AUTH.
Remove the following line:
server.login(user, pwd)
Hi I am not entirely sure why it's not working but I have got a few things you can check.
server = smtplib.SMTP('10.10.9.9: 25')
you got a space in the ip:port string, try removing it.
The ip:port combination seems to be from a private LAN address
Try to ping this address to see if you can reach it, If you can't then talk to the person who handles the machine with given ip in your network.
If you can ping the ip, then there is a possibility that the SMTP server is not available on the given port, In that case too contact the person responsible for managing the machine with IP: 10.10.9.9
use given command on terminal
ping 10.10.9.9
Also before login and and sendmail, you should connect to server using connect(), The correct order would be.
server = smtplib.SMTP('10.10.9.9: 25')
server.starttls()
server.connect('10.10.9.9', 465)
server.login(user, pwd)
server.sendmail(user, recipients, msg.as_string())
server.close()
465 is the default port for SMTP server
Thanks,
Let me know If It helped you!

Crash when sending email in Python 2.7.10

I'm trying to send an email within python, but the program is crashing when I run it either as a function in a larger program or on it's own in the interpreter.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = "exampleg#gmail.com"
toaddr = "recipient#address.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Hi there"
body = "example"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "Password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
In the interpreter, it seems to fail with server = smtplib.SMTP('smtp.gmail.com', 587)
Any ideas?
My standard suggestion (as I'm the developer of it) is yagmail.
Install: pip install yagmail
Then:
import yagmail
yag = yagmail.SMTP(fromaddr, "pasword")
yag.send(toaddr, "Hi there", "example")
A lot of things can be made easier using the package, such as HTML email, adding attachments and avoiding having to write passwords in your script.
For the instructions to all of this (and more, sorry for the cliches), have a look at the readme on github.
That's because you are getting error when trying to connect Google SMTP server.
Note that if you are using Google SMTP you should use:
Username: Your gmail address
Password: Your gmail password
And you should be already logged in. If you still get an error, you should check what is the problem in this list: https://stackoverflow.com/a/25238515/1600523
Note: You can also use your own SMTP server.

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"

Python smtplib security

I was experimenting with an email python script and was wondering if when writing a python-based email script is it is less secure as opposed to when credentials are send over the internet when logging into a web page? In the following script, are the user and pass in the clear?
import smtplib
from email.mime.text import MIMEText
GMAIL_LOGIN = 'xxxxxx#gmail.com'
GMAIL_PASSWORD = 'amiexposed?'
def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=GMAIL_LOGIN):
msg = MIMEText(message)
msg['Subject'] = 'Test message'
msg['From'] = from_addr
msg['To'] = to_addr
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(GMAIL_LOGIN,GMAIL_PASSWORD)
server.sendmail(from_addr, to_addr, msg.as_string())
server.close()
if __name__ == '__main__':
send_email('testing email script', 'This is a test message')
That would entirely depend how the TLS connection is set up. If you are requiring valid certificates (I believe if a certificate which is not trusted is encountered, your startTLS method will throw an exception (I'm not sure you should verify this)). But considering you are setting up TLS, and sending everything over the TLS connection, everything should be encrypted. This means neither your password, username or even your message and addressees will be sent in plain text.
So no, your username and password are not send clear.

Cannot send an email with python smtp

I am developing an application using python where I need to send a file through mail. I wrote a program to send the mail but dont know there's something wrong. The code is posted below. Please any one help me with this smtp library. Is there's anything i m missing? And also can someone please tell me what will be the host in smtp! I am using smtp.gmail.com.
Also can any one tell me how can i email a file (.csv file). Thanks for the help!
#!/usr/bin/python
import smtplib
sender = 'someone#yahoo.com'
receivers = ['someone#yahoo.com']
message = """From: From Person <someone#yahoo.com>
To: To Person <someone#yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
You aren't logging in. There are also a couple reasons you might not make it through including blocking by your ISP, gmail bouncing you if it can't get a reverse DNS on you, etc.
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(account, password)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
I just noticed your request to be able to attach a file. That changes things since now you need to deal with encoding. Still not that tough to follow though I don't think.
import os
import email
import email.encoders
import email.mime.text
import smtplib
# message/email details
my_email = 'myemail#gmail.com'
my_passw = 'asecret!'
recipients = ['jack#gmail.com', 'jill#gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'
# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))
# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())

Categories