I am trying to write a python script which sends a html code from my mail id to the target mail id.
It reads the following :
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "prudhvi#domainname.com"
you = "aditya#domainname.com"
msg = MIMEMultipart('multipart')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
</p>
</body>
</html>
"""
part = MIMEText(html, 'html')
msg.attach(part)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
I have tried running it and came across this error :
Traceback (most recent call last):
File "C:/Users/admin/Desktop/samp.py", line 29, in <module>
s = smtplib.SMTP('localhost')
File "C:\Python27\Lib\smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\Lib\smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\Lib\smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "C:\Python27\Lib\socket.py", line 575, in create_connection
raise err
error: [Errno 10061] No connection could be made because the target machine actively refused it
Could I know where I am going wrong?
I have solved my problem by doing the following :
1.) Providing Username and Password.
2.) Set the low security in google ON.
The code :
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "prudhvir36#gmail.com"
you = "prudhvi.g#domainname.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('prudhvir36', '*************')
mail.sendmail(me, you, msg.as_string())
mail.quit()
Related
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
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)
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'
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.
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.