I am developing a website with django framework. And I recently tried to release it on a 1&1 shared hosting.
I managed to make the project run well, except for one last “detail”: I can't send email from django.
I tried almost everything in settings (different emails, ports, etc.), but each time I got a beautiful '500 Internal Server Error' =/ (whereas it went fine on a free alwaysdata server)
In order to find the origin of this issue, I tried different things:
to test send_mail and EmailMessage via the python interpreter:
>>> send_mail('a subject', 'a test message', 'mymail#gmail.com', ['mymail#gmail.com'])
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: a subject
From: mymail#gmail.com
To: mymail#gmail.com
Date: Tue, 14 Jan 2014 22:12:48 -0000
Message-ID: <20140114221248.6718.86150#infong-fr25.kundenserver.de>
a test message
-------------------------------------------------------------------------------
1
But... I got nothing in my inbox.
My settings being:
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
DEFAULT_FROM_EMAIL = 'mymail#gmail.com'
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_PORT = 587
to connect to an SMTP server via the python interpreter:
./manage.py shell
>>> from smtplib import SMTP
>>> smtp_conn = SMTP()
>>> smtp_conn.connect('smtp.gmail.com', 25)
And nothing happens (I tried it with auth.smtp.1and1.fr, or port 587...); when I interrupt the process, it tells me:
^CTraceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.6/socket.py", line 554, in create_connection
sock.connect(sa)
File "<string>", line 1, in connect
KeyboardInterrupt
to test with a php file:
With a basic:
<?php
if (mail("mymail#gmail.com", "a subject", "a test")) {
echo("<p>Email successfully sent!</p>");
}
else {
echo("<p>Email delivery failed…</p>");
}
?>
And the mail was sent! So, it seems that without SMTP connection, it is possible (at least, via php).
Conclusion
So, my questions are: do you think I can manage to correct this bug, and otherwise is it possible to send mail without smtp connection ("like php")?
1and1 does not allow SMTP within 1and1. To send an email when running on 1and1...
#!/usr/bin/python
import os
mail_to = "sam#comcast.net"
mail_from = "steve#example.com"
subject = "test message"
header = """From: {0}
To: {1}
Subject: {2}
""".format(mail_from, mail_to, subject)
msg = header + "a test from me"
sendmail = os.popen("/usr/lib/sendmail -t", "w")
sendmail.write(msg)
sendmail.close()
The blog post linked shows an example that sends mail using SMTP through 1and1 via an external machine. Perhaps you can override Django's send_mail (or maybe this gives you [or someone else] a hint as to why it doesn't work.) This should allow you to send email in the Python interpreter, anyway.
Source: https://flenniken.net/blog/send-email-using-python-and-1and1/
Related
have been stuck on this for a few hours. Trying to send email from Python via Gmail SMTP
Gmail settings:
2 Step-Verification: Yes
App password created: Yes
Publishing status: Testing
User type: External
Code:
import smtplib
import ssl
port = 465 # For SSL
password = "example"
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login("test#gmail.com", password)
sender_email = "test#gmail.com"
receiver_email = "test#gmail.com"
message = """\
Subject: Test
Test."""
server.sendmail(sender_email, receiver_email, message)
This is the error message I'm getting:
Traceback (most recent call last):
File "C:\Users\coopejo\PycharmProjects\pythonProject1\trawler\gmaillogin.py", line 20, in <module>
server.sendmail(sender_email, receiver_email, message)
File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 876, in sendmail
(code, resp) = self.mail(from_addr, esmtp_opts)
File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 540, in mail
self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 373, in putcmd
self.send(str)
File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 365, in send
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
Any help would be greatly appreciated.Thanks!
So the error raised is asking you to run connect() first, so it looks like you aren't connecting to the server before trying to send the email.
I would put the server.sendemail() line directly under the server.login() line, with the same indent. That way, the already-connected server object is used for both. That's how it works in my code.
However, you're in bad luck here. As of May 30th, Google no longer allows insecure third-party apps to send emails this way. I'm looking into using a more secure auth method now and I'll update you if I find a working method.
I have written a code in jython 2.5, which uses the smtplib sendmail to send mail over a smtp server. Below is a simple snippet of the code
mail = MIMEMultipart('mixed')
mail['Subject'] = mail_subject
mail['FROM']=UstrSender
mail['To']=UstrReceivers
mail['Cc']=UstrCC
mail_p2=MIMEText(mail_html, 'html', 'utf-8')
mail.attach(mail_p2)
#Connection to SMTP
#Enter SMTP Server Details, In case your server do require authentication modify authentication parameter below and uncomment
s = smtplib.SMTP(smtpserver)
#s.sendmail(UstrSender, [UstrReceivers, UstrCC], mail.as_string())
sendmail_return = s.sendmail(UstrSender, [UstrReceivers, UstrCC], mail.as_string())
Now, the smtp server mentioned is a cluster of 3 individual servers and there is a lag at times on one of these servers because of a long queue of requests. To identify such issues and the culprit server, need to have a generic script to identify the queue id of the message being sent. Kindly, help on the same, if using docmd we can create such a command to get the queue id of the submitted email.
I tried getting a response from sendmail itself, but since the mail is eventually sent, there is no return from the command.
Thanks,
Dev
I started a little Raspberry project and stuck with sending a simple E-Mail. Gmail smtp is set up. The code works fine from Thonny (although it sends the E-Mal only for the first receiver and not both), but when I trigger it from the terminal (python report.py), I get the following Error:
Traceback (most recent call last):
File "report.py", line 15, in <module>
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
TypeError: __init__() got an unexpected keyword argument 'context'
As I mentioned above, from Thonny it is working. I plan to trigger some script like this time scheduled through Crontab. I set up the Crontab file, but it does nothing, I assume because it makes an error every time.
Thank you for help in advance!
The report.py content:
import smtplib, ssl
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "****#gmail.com"
receiver_email = "****#gmail.com,xxxx#gmail.com"
password = "****"
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
The context argument to smtplib.SMTP_SSL was added in Python 3.3.
Thonny uses a built-in Python3.7 interpreter, but many Unix-like operating systems' default Python interpreter is Python 2.x. Explicitly call the script with Python 3 to prevent the error:
python3 report.py
I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.
In my settings.py, I have these settings:
EMAIL_HOST = 'mail.privateemail.com'
EMAIL_HOST_USER = 'contact#mysite.com'
EMAIL_HOST_PASSWORD = 'my password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
And I am trying to send the email through a view:
send_mail(
'Subject here',
'Here is the message.',
'contact#mysite.com',
['myname#gmail.com'],
fail_silently=False,
)
However, I get this error:
SMTPException at /
STARTTLS extension not supported by server.
Any idea why? Any help is appreciated.
EDIT
After changing the EMAIL_USE_TLS to False, and also removing it to check both separately, I get this error now:
SMTP AUTH extension not supported by server.
Any idea why? Thanks!
your server mail.privateemail.com does not know what is STARTTLS SMTP Commnad is
this may happen in two cases:
your server (mail.privateemail.com) do not support secure communication at all and you need to use plain, non-encrypted communication.
you are trying to connect to the port that is already using SSL as the communication, then STARTTLS to upgrade connection to secure make no sense whatsoever.
your server is configured improperly and ignores STARTTLS on submission port (587).
Judging, that you are connecting to port 587 which should provide plain communication - it's either 1 or 3.
If you want this just work, remove EMAIL_USE_TLS = True or set it to False, otherwise - SMTP server configuration should be fixed.
You may try SSL instead of TLS by making following changes in settings.py
EMAIL_USE_SSL = True
EMAIL_PORT = 465
hope that helps
Either setup TLS on your mail server or use EMAIL_USE_TLS = False.
I am able to resolve the issue with modifying below line of code, by adding port number with server name:
server = smtplib.SMTP('mail.mycompany.com:587')
Not sure if you have solved the problem yet. I also recently try the 2-month free private email package from NameCheap. Here is my code and it works for me as of Jan 2018:
import smtplib
from email.message import EmailMessage
fromaddr = 'account#yourdomain.com'
toaddrs = "recipient#somedomain.com"
SMTPServer = 'mail.privateemail.com'
port = 465 #587
login = "account#yourdomain.com"
password = "password"
msg = EmailMessage()
msgtxt = "http://www.google.com"+"\n\n"+"This is a test."
msg.set_content(msgtxt)
msg['Subject'] = "Test message"
msg['From'] = fromaddr
msg['To'] = toaddrs
server = smtplib.SMTP_SSL(SMTPServer, port) #use smtplib.SMTP() if port is 587
#server.starttls()
server.login(login, password)
server.send_message(msg)
server.quit()
Hope this help!
PS. You can also use port 587, but you have to use smtplib.SMTP() instead of smtplib.SMTP_SSL(), and also have to un-comment the server.starttls() line.
I googled a lot about this problem, and i found this error in a plenty of locations, but no answer for my problem.
I' ve a newly installed (debian) system, which contains basically only a django (1.3.0) installation, and a very poor postfix. Postfix is working, if i do
echo sth | mail somebody#provider.com
it arrives perfectly.
I tried to use django send_mail like
from django.core.mail import send_mail
send_mail('aaa', 'bbb', 'from#localhost', ['user#external.hu'])
but I get back always an error:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/dist-packages/django/core/mail/__init__.py", line 61, in send_mail
connection=connection).send()
File "/usr/lib/python2.6/dist-packages/django/core/mail/message.py", line 248, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/lib/python2.6/dist-packages/django/core/mail/backends/smtp.py", line 92, in send_messages
sent = self._send(message)
File "/usr/lib/python2.6/dist-packages/django/core/mail/backends/smtp.py", line 110, in _send
email_message.message().as_string())
File "/usr/lib/python2.6/smtplib.py", line 709, in sendmail
raise SMTPRecipientsRefused(senderrs)
SMTPRecipientsRefused: {'user#external.hu': (554, '5.7.1 : Relay access denied')}
Certainly I tried with different addresses. The only one cases when he delivers the email is the one, when I send it to localhost (or to hosts having mx on this machine).
In the mail.log I can see this:
Apr 16 10:48:48 tkt postfix/smtpd[4886]: connect from tkt[217.112.142.235]
Apr 16 10:48:48 tkt postfix/smtpd[4886]: NOQUEUE: reject: RCPT from tkt[217.112.142.235]: 554 5.7.1 : Relay access denied; from= to= proto=ESMTP helo=
Apr 16 10:48:48 tkt postfix/smtpd[4882]: lost connection after RSET from tkt[217.112.142.235]
Apr 16 10:48:48 tkt postfix/smtpd[4882]: disconnect from tkt[217.112.142.235]
Sniffing port 25 I can see nothing.
Anyone any idea how to solve this problem (using the local postfix most prefereably)?
The machine is on the Internet site, and as I wrote, mail sending works ok from command line.
I'm not 100% sure, but I think the difference between...
echo sth | mail somebody#provider.com
...and...
send_mail('aaa', 'bbb', 'from#localhost', ['user#external.hu'])
...is that the former is connecting to postfix on IP address 127.0.0.1, but the latter is connecting to postfix on IP address 217.112.142.235, although I'm not sure why. It might depend on which IP address your webserver is bound to.
Postfix is typically configured by default to only allow email to be relayed when connected to on 127.0.0.1 for security reasons.
You can either change your Django settings.py to force it to use 127.0.0.1 by adding...
EMAIL_HOST='localhost'
...or reconfigure postfix to allow relaying from 217.112.142.235 by changing the mynetworks param in /etc/postfix/main.cf from something like...
mynetworks = 127.0.0.0/8
...to something list...
mynetworks = 127.0.0.0/8 217.112.142.235/32
...then do...
sudo service postfix restart
...to make it re-read the confing.