bepolytech / ULBDiscordBot

Discord bot to verify a user's ULB studentship
https://hub.docker.com/r/bepolytech/ulbdiscordbot
GNU General Public License v3.0
4 stars 1 forks source link

Add possibility to send email from an alias #22

Open LucasPlacentino opened 1 year ago

LucasPlacentino commented 1 year ago

Use the "From" field of the email content with an alias that is registered with the gmail account used to login to the gmail api. Like use a noreply@... with the bot account.

In classes/admin.py :

_email_addr: str = os.getenv("EMAIL_ADDR")
    _port = 465  # For SSL
    _auth_token: str = os.getenv("EMAIL_AUTH_TOKEN")
    _context: ssl.SSLContext = ssl.create_default_context()

    @classmethod
    def _content(cls, target_email: str, token: str):
        """Create email content.
        Parameters
        ----------
        target_email: `str`
            The email address of the receiver
        token: `str`
            The token to inlude in the email
        """
        msg = MIMEMultipart("alternative")
        msg["Subject"] = "Discord - ULB email adresse vérification"
        msg["From"] = cls._email_addr
        msg["To"] = target_email

Here could have a cls._sender_email_addr as an extra argument to cls._content(...), and also use it for server.sendmail ? (need to test it).
server.login should remain as is, with the account email address.

with smtplib.SMTP_SSL("smtp.gmail.com", cls._port, context=cls._context) as server:
            server.login(cls._email_addr, cls._auth_token)
            content: str = cls._content(target_email, token)
            server.sendmail(cls._email_addr, target_email, content)
            logging.trace(f"[EMAIL] Token email sent to {target_email}")

And define _sender_email_addr = os.getenv("SENDER_EMAIL_ADDR") in here, and the .env

class EmailManager:
    """Represent the email manager.
    This should be used as a class, and not instantiated.
    Classmethods
    -----------
    send_token(targer_email: `str`, token: `str`)
        Send an email for the token verification
    """

    _email_addr: str = os.getenv("EMAIL_ADDR")
    _port = 465  # For SSL
    _auth_token: str = os.getenv("EMAIL_AUTH_TOKEN")
    _context: ssl.SSLContext = ssl.create_default_context()
LucasPlacentino commented 1 year ago

I need to test this :)