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 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 465
Connected to

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):

class MailManager:
    def init_app(self, app): = 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.port, self.password, self.username):
            raise MailManagerNotConfigured(
                "Ensure you have configured all the required MAIL_* environment variables."
            )"Sending email via {} - {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")

        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(, 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 465 directly.

But it was definitely set to

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


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

fly secrets set
1 Like