Home > OS >  GCP (Google Cloud) VM - Can't send email via Python script with SMTP
GCP (Google Cloud) VM - Can't send email via Python script with SMTP

Time:09-17

So I set up a GCP VM with Ubuntu, from where I want to send regular reports through my mail provider with a python script. The smtp port is 587, and to my understanding the port was formerly closed in GCP environments but should now be available.

My script looks like this:

import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import time


timestr = time.strftime('(%Y-%m-%d)')
username='[email protected]'
password='secretpw'
send_from = '[email protected]'
send_to = '[email protected]'
body = 'hello'

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = 'important email'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(','), msg.as_string())
smtp.quit()

On execution, the machine takes some time before outputting a timeout:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    server = smtplib.SMTP('smtp.ionos.de')
  File "/usr/lib/python3.8/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.8/smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out

I can, however, ping smtp.ionos.de as well as telnet smtp.ionos.de 587 form the cl with result of a working ping and connection.

I also tried this with other email providers including gmail and get stuck with the exact same outcome.

Anyone? Help appreciated, thanks.

CodePudding user response:

Your code has multiple problems:

  • Connecting to the server twice.
  • Not specifying the port number when connecting
  • Not creating an SSL context for encryption.

In your code, replace these lines:

server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()

With:

context = ssl.create_default_context()
smtp = smtplib.SMTP('smtp.ionos.de', 587)
smtp.ehlo()
smtp.starttls(context=context)
  • Related