Beispiel #1
0
    def __init__(self, addr_from, subject, text="", html=""):
        """
        Constructs Sendgrid Message object

        Args:
            addr_from: From address, email "*****@*****.**" or tuple ("*****@*****.**", "John, Doe")
            subject: Email subject
            text: Email content, plain text
            html: Email content, html

        Returns:
            self

        Raises:
            ValueError: on invalid arguments
        """
        if not text and not html:
            raise ValueError("Either html or text should be provided")

        self.from_name = ''
        self.from_address = addr_from
        if isinstance(addr_from, tuple):
            (self.from_address, self.from_name) = addr_from
        self.to_name = []
        self.reply_to = ''
        self.to = []
        self.subject = subject
        self.html = html
        self.text = text
        self.cc = []
        self.bcc = []
        self.headers = {}
        self.attachments = []
        self.header = SmtpApiHeader()
        self.date = rfc822.formatdate()
Beispiel #2
0
    def add_to(self, recipients, names=None):
        """
        Add recipient

        Args:
            recipients: recipient, accepts string, list or dict
                if dict is passed, "To" field will be ignored and batch sending with substitution triggered
            names:  recipient names, string or list

        Returns:
            self
        """
        if not recipients:
            raise ValueError('No recipients')

        if isinstance(recipients, (str, unicode)):
            self.to += [recipients]
            if names:
                self.to_name += [names]
            else:
                self.to_name += [""]

        elif isinstance(recipients, dict):
            subvals = {}
            to = []
            for email in recipients:
                to.append(email)
                for subval in recipients[email]:
                    if not subval in subvals:
                        subvals[subval] = []

                    subvals[subval].append(recipients[email][subval])

            for subval in subvals:
                if len(subvals[subval]) != len(to):
                    self.header = SmtpApiHeader()
                    raise ValueError(
                        'Sub values count should be equal to recipients count')
                self.header.add_sub_val(subval, subvals[subval])

            self.header.add_to(to)
            self.to = [to[0]]

        else:
            self.to += recipients
            if names:
                if len(recipients) != len(names):
                    raise ValueError(
                        'Assigned names count should be equal to recipient address count'
                    )
                else:
                    self.to_name += names
            else:
                for recipient in recipients:
                    self.to_name += [""]

        return self