Why won't an email send in my Python CGI script using Apache?

Viewed 87

I have written a basic CGI script in Python which takes in an email address and attempts to send an email to that address. The script runs from the command line and an email is successfully sent. However, when I attempt to run the CGI script through apache I get the following error in apache logs. I believe it may be something to do with underprivileged users not being able to access a port necessary to send email. What can I do so that my emails will send?

[Tue Mar 16 22:25:36.961156 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:   File "/usr/lib64/python2.7/smtplib.py", line 255, in __init__
[Tue Mar 16 22:25:36.961223 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:     (code, msg) = self.connect(host, port)
[Tue Mar 16 22:25:36.961277 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:   File "/usr/lib64/python2.7/smtplib.py", line 315, in connect
[Tue Mar 16 22:25:36.961327 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:     self.sock = self._get_socket(host, port, self.timeout)
[Tue Mar 16 22:25:36.961382 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:   File "/usr/lib64/python2.7/smtplib.py", line 290, in _get_socket
[Tue Mar 16 22:25:36.961431 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:     return socket.create_connection((host, port), timeout)
[Tue Mar 16 22:25:36.961490 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:   File "/usr/lib64/python2.7/socket.py", line 571, in create_connection
[Tue Mar 16 22:25:36.961504 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215:     raise err
[Tue Mar 16 22:25:36.961540 2021] [cgi:error] [pid 26389] [client 81.153.140.181:55178] AH01215: socket.error: [Errno 13] Permission denied

Here is the script

#!/usr/bin/env python

import cgi, cgitb
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

form = cgi.FieldStorage()

email = form.getvalue('EMAIL')

msg = MIMEMultipart()
msg['From'] = '<email_from>'
msg['To'] = email
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.ionos.co.uk',587)
#mailserver.ehlo()
#mailserver.starttls()
#mailserver.ehlo()
#mailserver.login('<user>', '<password>')

#mailserver.sendmail('<email_from>', email, msg.as_string())

#mailserver.quit()

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>I have sent an email to %s</h2>" % (email)
print "</body>"
print "</html>"

I am running this on an CentOS AWS instance.

0 Answers
Related