Few hours back I have posted a post related to "Django email sending API" and its error. So I thought that first I should try something with "smtplib". Unfortunately, after struggling with "smtplib", I realise that it will also not work, because something is wrong with my code or my network or my machine which I am not able to figure out.
Can any body help me regarding to this?
As of now, after struggling a lot, I have tried hundreds of solution posted here and there and also I have tried to resolve with myself but nothing is working in my case kindly help.
Code is given bellow.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "172.16.0.2", '8084')
socks.wrapmodule(smtplib)
#smtp = smtplib.SMTP()
msg = MIMEMultipart()
msg['From'] = 'my#yahoo.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('my#yahoo.com', 'pswd12345678')
mailserver.sendmail('my#yahoo.com','example#gmail.com',msg.as_string())
mailserver.quit()
This is the error coming again and again:
Traceback (most recent call last):
File "import_mail.py", line 21, in <module>
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -3] Temporary failure in name resolution
This error is raised as the 'EMAIL_BACKEND' definition is missing from the settings file. Make sure that the settings.py file contains the following line:-
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
IF you`re using the gmail account to set up a default interactive mail, use the following values:-
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587 #PORT NO
EMAIL_HOST_USER = #e-MAIL ID
EMAIL_HOST_PASSWORD = #PASSWORD
My system had not a DNS configured and I resolved this issue configuring a google DNS or an openDNS.
Related
I have a setup where I am using "send_mail" to send emails to the users using a gmail account. For some reason this function returns "smtplib.SMTPServerDisconnected: Connection unexpectedly closed".
I am using a gmail account with 2 factor security enabled and an app password.
If I just build a script using smtplib, it works. I am not sure how exactly to debug this issue.
Edit 1:
'send_mail' Seems to work if I remove "**connection_params" from being passed to "self.connection_class" on line 81 in 'django/core/mail/backends/smtp.py'
Edit 2:
Changing "smtpObj = smtplib.SMTP('smtp-relay.gmail.com', 587)" to "smtpObj = smtplib.SMTP('smtp-relay.gmail.com', 587, local_hostname='localhost')" results in the same error in case of smtplib
The problems seems to lie in the following:
value "localhost" is assigned to "connection_params" on line 69 in 'django/core/mail/backends/smtp.py' in the following manner (you may notice, there is no 'if' check, as the comment states):
...
# If local_hostname is not specified, socket.getfqdn() gets used.
# For performance, we use the cached FQDN for local_hostname.
connection_params = {"local_hostname": DNS_NAME.get_fqdn()}
...
The problem is, there is no way to assign 'local_hostname', as far as I can see, nor is there a way to set it to None
Edit 3:
It looks like Django is trying to do a 'socket.getfqdn()', which returns 'localhost', but 'localhost' is not fully qualified. Smtplib does the same 'socket.getfqdn()', but check for localhost and sets it to '127.0.0.1' instead.
This seems like a bug, with no way to set the 'local_hostname' value, and automatically setting it to 'localhost' which is not fully qualified.
Code snippets below:
settings.py
...
EMAIL_HOST = 'smtp-relay.gmail.com'
EMAIL_HOST_USER = "myemail#costumgmail.com"
EMAIL_HOST_PASSWORD = "mypass"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
...
djangotest.py
from django.core.mail import send_mail
send_mail('Django mail', 'This e-mail was sent with Django.', "myemail#costumgmail.com" , ['some.other#mail.com'], fail_silently=False)
# smtplib.SMTPServerDisconnected: Connection unexpectedly closed
smtplibtest.py
from email.message import EmailMessage
import smtplib
email_sender = "myemail#costumgmail.com"
email_password="mypass"
email_reciever ='some.other#mail.com'
subject = "test"
body = "test"
em = EmailMessage()
em['sender'] = email_sender
em['to'] = email_reciever
em['subject'] = subject
em.set_content(body)
smtpObj = smtplib.SMTP('smtp-relay.gmail.com', 587)
smtpObj.ehlo() # (250, b'smtp-relay.gmail.com at your service, [188.26.233.149]\nSIZE 157286400\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
smtpObj.starttls() # (220, b'2.0.0 Ready to start TLS')
smtpObj.login(email_sender, email_password) # (235, b'2.7.0 Accepted')
smtpObj.sendmail(email_sender, email_reciever, em.as_string()) # OK
traceback from django:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail
return mail.send()
File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send
return self.get_connection(fail_silently).send_messages([self])
File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages
new_conn_created = self.open()
File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 87, in open
self.connection.starttls(
File "/usr/lib/python3.10/smtplib.py", line 769, in starttls
self.ehlo_or_helo_if_needed()
File "/usr/lib/python3.10/smtplib.py", line 612, in ehlo_or_helo_if_needed
(code, resp) = self.helo()
File "/usr/lib/python3.10/smtplib.py", line 441, in helo
(code, msg) = self.getreply()
File "/usr/lib/python3.10/smtplib.py", line 405, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I've script written in Python3, it's doing couple of things and one of them is sending email. That's the code:
import smtplib
import os
import json
import re
from datetime import datetime
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
message = MIMEMultipart()
message['Subject'] = mailtitle
message['From'] = mailfrom
message['To'] = mailto
body_content = ("Text message")
message.attach(MIMEText(body_content, 'plain'))
msg_body = message.as_string()
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(message['From'], message['To'], msg_body)
server.quit()
It's working fine on my virtual box environment but when I've put it on real testing environment I'm getting below output:
Traceback (most recent call last):
File "send_email.py", line 166, in <module>
send_mail()
File "send_email.py", line 159, in send_mail
server = smtplib.SMTP('localhost')
File "/usr/lib64/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
OSError: [Errno 113] No route to host
Could you pls advise what can cause the issue? Firewall settings? Missing libraries?
Many thanks
I resolved that issue in the end. The problem was related to the blocked SMTP port 25 on the firewall. When the port has been opened, my issue disappeared.
when I try to send an email with email module I get error
I tried with 3 different mail provider
and it is my code :
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
message = MIMEMultipart()
message["from"] = "Amir Mohammad Fallah"
message["to"] = "*******#gmail.com"
message["subject"] = "python test message"
message.attach(MIMEText("body"))
password = "*******"
user = "*********#gmail.com"
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol
smtp.ehlo()
smtp.login(user, password)
smtp.send_message(message)
print("it's Done !")
and I after while I got this errors :
Traceback (most recent call last):
File "/Users/mgxc2/PycharmProjects/Advance/Python.py", line 588, in <module>
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol #mail.cortatech.ir port 587
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
First and foremost I think you should change with smtplib.SMTP("smtp.gmail.com", 465) to with smtplib.SMTP("smtp.gmail.com", 587) and see what happens... Secondly, you should change your Internet connection, because your code looks okay to me.. but I'll check it soon to know the cause, but first try the corrections I sent across
You should use port 587 because it's the default mail submission port.
Here is an articles that explain witch SMTP port to use for witch action.
I am trying to send an email via Python from my Office 365 corporate account to another Office 365 corporate account. The objective is to send an email once the script runs successfully.
I've checked the email ID and password, however, can't seem to figure out what the problem is.
import smtplib
message = "Execution Successful"
mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('userid#corporateemail.com', 'password')
mailserver.sendmail('userid#corporateemail.com', 'userid#corporateemail.com', message)
mailserver.quit()
This should trigger an email to the user. However, it gives an error message.
Here is the output:
Traceback (most recent call last):
File "<ipython-input-45-663ff7ed4e61>", line 1, in <module>
runfile('C:/Users/qy115/Desktop/Updated Python/Test/EmailTest.py', wdir='C:/Users/qy115/Desktop/Updated Python/Test')
File "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/qy115/Desktop/Updated Python/Test/EmailTest.py", line 20, in <module>
mailserver.starttls()
File "C:\Software\Eng_APPS\Anaconda3\lib\smtplib.py", line 752, in starttls
(resp, reply) = self.docmd("STARTTLS")
File "C:\Software\Eng_APPS\Anaconda3\lib\smtplib.py", line 420, in docmd
return self.getreply()
File "C:\Software\Eng_APPS\Anaconda3\lib\smtplib.py", line 390, in getreply
+ str(e))
SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I'm trying to do the same thing. I don't think you can use username and password to authenticate anymore with Office 365. You have to follow these instructions which from what I understand requires you to connect to the Office 365 via a secure app in Microsoft Azure service:
https://pypi.org/project/O365/#different-authentication-interfaces
I have managed to authenticate, however, not able to retrieve the required token to get into my account and send an email. Maybe you will have better success? If anyone has done this successfully, please let us know as I can't work it out.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = "Hello, This is a simple mail. There is only text, no
attachments are there The mail is sent using Python SMTP library"
#The mail addresses and password
sender_address = 'userid#corporateemail.com'
sender_pass = 'XXXXXXXXX'
receiver_address = 'userid#corporateemail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
#The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')
I am using the following code below:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#...
def send_file_zipped(the_file, recipients, sender='email#email.com'):
myzip = open('file.zip', 'rb')
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(myzip.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", "587")
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
#running this
send_file_zipped('file.zip', 'email#email.edu')
I have tried different variations to try and make it connect successfully here, but I am at a loss here. The error I am getting is this:
Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 99, in <module>
send_file_zipped('file.zip', 'email#email.com')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 40, in send_file_zipped
smtp.connect()
File "/usr/local/lib/python3.2/smtplib.py", line 319, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.2/smtplib.py", line 294, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.2/socket.py", line 404, in create_connection
raise err
File "/usr/local/lib/python3.2/socket.py", line 395, in create_connection
sock.connect(sa)
socket.error: [Errno 61] Connection refused
I am going to assume that my issue lies in connecting with the smtp server, but I don't know what I am missing. Any help would be greatly appreciated!!
smtp.connect() is wrong/redundant. The smtplib.SMTP(...) calls .connect upon initialization. A bare .connect call without any parameters means connection to localhost and if you do not have a SMTP server running on your machine you'll get an error.
However your goal is to send mail through GMail. Note that GMail's SMTP requires authentication, which you are not doing.
Your last lines should be accordingly:
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.helo()
smtp.starttls() # Encrypted connection
smtp.ehlo()
smtp.login(username, password) # Give your credentials
smtp.sendmail(sender, recipients, themsg)
smtp.quit()
This may not be your problem, but you're specifying the port number as a string, and that's probably not going to work.