Error trying to send email to gmail python - python

Hi all I am new to python. I am trying to send an image to my gmail account and getting the below error can someone help me with this.
I have searched and searched and can't find an answer I have tried changing the port.
I have turned on the google less secure apps and not sure what else to do.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
gmail_user = "you#gmail.com"
gmail_pwd = "pass"
to = "you#gmail.com"
subject = "Report"
text = "Picture report"
attach = 'web.png'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 31, in <module>
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 393, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
i have changed the port to 587 and got a different error
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 35, in <module>
mailServer.login(gmail_user, gmail_pwd)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login
raise last_exception
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt4\n5.7.14 ah5smKPNBMdR8EDhHji_lOLermVkofD0XZiYZtx04cUZGJIvjm6scA9FeCEhJhB--aeW58\n5.7.14 O3uS9IVuNfqKe4HYqXgdBMbvtMSOSSMM4oGYwlvDIoXpIK0IJYKSyAfvPyPcjiF8Q_Es4n\n5.7.14 33gUceqr9ZjlNI066kXt-uTq2V39X6YUS2-ixCCKfoozS9zoQ1KJuLSWU1IhB3gTsGtB9m\n5.7.14 N-AEdgucbByvuI7zr2KG-DZwlvrWw> 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 b65sm27550600wrd.26 - gsmtp')

Your code can be shortened down to just two lines:
import smtplib
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
And if you get smtplib.SMTPServerDisconnected, this means that your question is not about the code. Something is blocking your network connection to port 465.

A SMTP server on port 465 is listening for encrypted TLS connections. The client is not supposed to start the encryption with STARTTLS, because TLS is active from the beginning. That SMTP command is used on port 587 where SMTP servers are listening for plaintext connections.

you can use flask_mail library for sending mail.Here is just quick review..
'
from flask_mail import Mail, Message
app.config['SECRET_KEY'] = 'your secretkey'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your gmail id'
app.config['MAIL_PASSWORD'] = 'and its password'
mail = Mail(app)
msg = Message(subject=subject, sender=(master().user(),
app.config['MAIL_USERNAME']), recipients=[recipients])
msg.body = "%s %s" % (body, msg.sender)
if html is not None:
msg.html = str(html)
mail.connect()
mail.send(msg)
'
***Note :- do not forget to turn off 2-step verification and also turn on Allow less secure apps from sign-in & security > device activity & security events

Related

How to send email attachments with Python 3.6

would you mind helping me, please!
I use all code's from this page How to send email attachments with Python
but it didn't work =(
This is last version which i used
import smtplib
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
filepath = 'D:/files/1.jpg'
fromaddr = "name#gmail.com"
toaddr = "name2#gmail.com"
password = '********'
mail_adr = 'smtp.gmail.com'
mail_port = 587
# Compose attachment
part = MIMEBase('application', "octet-stream")
part.set_payload(open(filepath, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(filepath))
# Compose message
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg.attach(part)
# Send mail
smtp = SMTP_SSL()
smtp.set_debuglevel(1)
smtp.connect(mail_adr, mail_port)
smtp.login(fromaddr, password)
smtp.sendmail(fromaddr, toaddr, msg.as_string())
smtp.quit()
and here are the errors I fall
connect: ('smtp.gmail.com', 587)
connect: ('smtp.gmail.com', 587)
Traceback (most recent call last):
File "C:/Users/Oleg/Desktop/444.py", line 31, in <module>
smtp.connect(mail_adr, mail_port)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 335, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 1037, in _get_socket
server_hostname=self._host)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 808, in __init__
self.do_handshake()
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:749)
Have you tried emailpy? (I am the author)
It supports any attachment format unless your email provider restricts it.
Example:
import emailpy
emailManager = emailpy.EmailManager('yourcooladdress#domain.com', 'youremailpassword') # this may take a few seconds to generate
emailManager.send(['sendsomething#gmail.com', 'anotheremail#hotmail.com'], \
subject = 'Subject here', body = 'body text here', html = 'some html here', \
attachments = ['file1.png', 'file2.txt', 'file3.py'], \
nofileattach = {'file.txt': 'hi, this is some data'})
# send email to sendsomething#gmail.com and anotheremail#hotmail.com with subject "Subject here"
#, body "body text here", html "some html here", and some attachments:
# "file1.png", "file2.txt", "file3.py". Also, it adds a file called file.txt
# that has the contents "hi, this is some data"
The emailpy docs can either be downloaded on its PyPI page, or from here
All email servers have been successfully tested with emailpy, and there will be no errors with emailpy if you use it on python 3.x (emailpy is not supported in python 2, mainly because of the syntax)

Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]

Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.
import smtplib
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "user#comany.com"
toaddr = str(sys.argv[1]).split(",")
ccaddr = str(sys.argv[2]).split(",")
bccaddr = str(sys.argv[3]).split(",")
subject = None
body = None
print sys.argv
with open("subject.txt") as f1:
subject = f1.read()
with open("body.txt") as f2:
body = f2.read()
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Cc'] = ccaddr
msg['Bcc'] = bccaddr
msg['Subject'] = subject.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
body = body.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
msg.attach(MIMEText(body, 'plain'))
for filename in str(sys.argv[5]).split(";"):
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, "password")
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
Here is the error:
File "send_mail.py", line 49, in <module>
server.sendmail(fromaddr, toaddr, msg.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 115, in _write
self._write_headers(msg)
File "/usr/lib/python2.7/email/generator.py", line 164, in _write_headers
v, maxlinelen=self._maxheaderlen, header_name=h).encode()
File "/usr/lib/python2.7/email/header.py", line 410, in encode
value = self._encode_chunks(newchunks, maxlinelen)
File "/usr/lib/python2.7/email/header.py", line 370, in _encode_chunks
_max_append(chunks, s, maxlinelen, extra)
File "/usr/lib/python2.7/email/quoprimime.py", line 97, in _max_append
L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'
Try it with yagmail. Disclaimer: I'm the developer of yagmail.
import yagmail
yag = yagmail.SMTP("user#comany.com", "password")
yag.send(toaddrs, subject, body, str(sys.argv[5]).split(";"), ccaddrs, bccaddrs)
# ^ to ^subject ^ body ^ attachments ^ cc ^ bcc
It's pretty much "Do What I Want", you can provide lists of strings or a single string, even omit any arguments, and it will be sensible. Another cool thing is that the attachments here is a list of strings; where each will be tried to be loaded as file (with correct mimetype).
Use pip install yagmail to install
I had the same problem when I tried to feed a list in to msg['To']. I changed the list to string and I got rid of the problem. ['test#my.com', 'another#my.com'] => 'test#my.com, another#my.com'

Python SMTP error: "(10013, 'Permission denied')"

So I have this Python send-email file that sends an email (the text from a file) to a recipient specified inside the code:
import smtplib
from email.mime.text import MIMEText
msgContent = open(Sourcefilelocation, "rb")
msg = MIMEText(spam.read())
msgContent.close()
msg['Subject'] = SUBJECT
msg['From'] = FROM_CLIENT_EMAIL
msg['To'] = TO_CLIENT_EMAIL
#THE ERROR BELOW
s = smtplib.SMTP('localhost')
I understand that there is no mail server on localhost, but how do I make a mail server on that and if I can't then why does s = smtplib.SMTP('gmail.com') take so long if it even works? What do I need to make it work? Any help is appreciated.
output: >> Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s = smtplib.SMTP('gmail.com')
File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10013, 'Permission denied')
And the gmail smtp code takes too long.

SSL Error while Sending Email with Python (Raspbian OS)

I just write this code in Python under Raspbian OS:
import smtplib
fromaddr = '*****#hotmail.de'
toaddrs = '*****#hotmail.de'
msg = 'Testmail'
username = '*****#hotmail.de'
password = '*****'
server = smtplib.SMTP('smtp.live.com',587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
And get following Error-Message:
python ail.py
Traceback (most recent call last):
File "ail.py", line 14, in <module>
server.login(username, password)
File "/usr/lib/python2.7/smtplib.py", line 601, in login
AUTH_PLAIN + " " + encode_plain(user, password))
File "/usr/lib/python2.7/smtplib.py", line 385, in docmd
return self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 358, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 1] _ssl.c:1359:
error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
What is my fault? Could somebody help me - please?
Regards
After I've signed in on http://live.com and validated my account; your code worked as is on Ubuntu python 2.7 and python3.3:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Send email via live.com."""
import smtplib
from email.mime.text import MIMEText
from email.header import Header
login, password = ...
msg = MIMEText(u'body…', 'plain', 'utf-8')
msg['Subject'] = Header(u'subject…', 'utf-8')
msg['From'] = login
recipients = [login]
msg['To'] = ", ".join(recipients)
s = smtplib.SMTP('smtp.live.com', 587, timeout=10)
s.set_debuglevel(1)
try:
s.starttls()
s.login(login, password)
s.sendmail(msg['From'], recipients, msg.as_string())
finally:
s.quit()
Check whether openssl can connect to it (ca-certificates is installed and it is not this bug):
$ openssl s_client -starttls smtp -connect smtp.live.com:587
If it is successful; you could replace smtplib.SMTP.starttls() method (in a subclass) to set appropriate ssl parameters.

Emailing smtp with Python error

I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes.
import smtplib
FROMADDR = "FROM_EMAIL"
LOGIN = "USERNAME"
PASSWORD = "PASSWORD"
TOADDRS = ["TO_EMAIL"]
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('OUTGOING_SMTP', 465)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
And here's the error I get:
Traceback (most recent call last):
File "emailer.py", line 13, in
server = smtplib.SMTP('OUTGOING_SMTP', 465)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail server so that only connections from within the school can send mail in this way.

Categories

Resources