Issues sending an email (outbound) via smtp

I’m using python to send a email via sendgrids smtp service. It’s working fine locally but when deployed on a fly VM I am getting the following error:

socket.gaierror: [Errno -2] Name or service not known

I’m using smtp.sendgrid.net on port 465. This looks like a DNS issue, but I can ping that host from the VM. I can also connect over telnet via the VM.

# telnet smtp.sendgrid.net 465
Trying 167.89.123.97...
Connected to smtp.sendgrid.net.

I doubt it’s related to the code but here is the bit responsible for sending the email.

import smtplib, ssl
from email.message import Message
import logging


class MailManagerNotConfigured(Exception):
    pass


class MailManager:
    def init_app(self, app):
        self.host = app.config.get("MAIL_HOST")
        self.port = app.config.get("MAIL_PORT")
        self.password = app.config.get("MAIL_PASSWORD")
        self.username = app.config.get("MAIL_USERNAME")
        self._from = app.config.get("MAIL_FROM")
        app.mail_manager = self

    def send(self, to, subject, body):
        if None in (self._from, self.host, self.port, self.password, self.username):
            raise MailManagerNotConfigured(
                "Ensure you have configured all the required MAIL_* environment variables."
            )

        logging.info(f"Sending email via {self.host} - {self.username}")

        message = Message()
        message.add_header("from", self._from)
        message.add_header("to", to)
        message.add_header("subject", subject)
        # Always send html emails.
        message.add_header("Content-Type", "text/html")
        message.set_payload(body)

        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(self.host, self.port, context=context) as server:
            server.login(self.username, self.password)
            server.sendmail(self._from, to, message.as_string())


mail_manager = MailManager()

Has anyone bumped into anything similar? Any advice?

Is MAIL_HOST set on your VM? You can check by logging in with fly ssh console and typing `env’.

Hi Joshua,

Thanks for getting back to me so quick. So while I was confirming that MAIL_HOST was set. I thought I’d try telnet $MAIL_HOST $MAIL_PORT to ensure I could connect via the envars, this threw another DNS error, before I’d just been running telnet smtp.sendgrid.net 465 directly.

But it was definitely set to smtp.sendgrid.net

A bit more investigating and I found that the .env file that I was importing secrets from looked like this:

MAIL_HOST="smtp.sendgrid.net"

I then removed the quotes and set the secret and then things started working.

fly secrets set MAIL_HOST=smtp.sendgrid.net
1 Like