Commit f352d38d authored by Cristiano Urban's avatar Cristiano Urban
Browse files

Added support for attachments.

parent 1fb35ab9
Loading
Loading
Loading
Loading
+46 −12
Original line number Diff line number Diff line
#!/usr/bin/env python

import mimetypes
import smtplib

from config import Config
from email.message import EmailMessage
from email.policy import SMTP
from smtplib import SMTPException


class Mailer(object):
@@ -13,28 +17,58 @@ class Mailer(object):
        self.smtpServer = params["smtp_server"]
        self.smtpPort = params.getint("smtp_port")
        self.sender = params["no_reply_email"]
        self.receivers = []
        self.recipients = []
        self.message = None

    def sender(self, sender):
        """Set mail sender."""
        self.sender = sender

    def addReceiver(self, receiver):
        self.receivers.append(receiver)
    def addRecipient(self, recipient):
        """Add recipient to recipients list."""
        self.recipients.append(recipient)

    def setMessage(self, msg):
        self.message = msg
    def setMessage(self, subject, msg):
        """Set a basic message."""
        self.message = EmailMessage()
        self.message["From"] = self.sender
        self.message["Subject"] = subject
        self.message["To"] = ", ".join(self.recipients)
        self.message.set_content(msg)

    def setMessageWithAttachment(self, subject, msg, filePath):
        """Set a message with attachment."""
        self.setMessage(subject, msg)
        ctype, encoding = mimetypes.guess_type(filePath)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"
        maintype, subtype = ctype.split('/', 1)
       
        with open(filePath, "rb") as fp:
            self.message.add_attachment(fp.read(),
                                        maintype = maintype,
                                        subtype = subtype,
                                        filename = filePath)

    def send(self):
        """Send email message."""
        try:
            smtpObj = smtplib.SMTP(self.smtpServer, self.smtpPort)
            smtpObj.sendmail(self.sender, self.receivers, self.message)
            smtpObj.send_message(self.message)
            print("Message sent!")
        except SMTPException:
            print("Error: cannot send email message.")

# Test
#m = Mailer()
#m.setMessage("Hello world!")
#m.addReceiver("cristiano.urban@inaf.it")
#m.send()

# Test 1
#m1 = Mailer()
#m1.addRecipient("cristiano.urban@inaf.it")
#m1.setMessage("Hello", "Hello world!")
#m1.send()

# Test 2
#m2 = Mailer()
#m2.addRecipient("cristiano.urban@inaf.it")
#m2.addRecipient("cristiano.urban.slack@gmail.com")
#m2.setMessageWithAttachment("Hello", "Hello world!", "config.py")
#m2.send()