Exemple #1
0
    def test_unicode_complex_message(self):
        charset = 'utf-8'
        p1 = MIMEText(
            '''По оживлённым берегам
Громады стройные теснятся
Дворцов и башен; корабли
Толпой со всех концов земли
К богатым пристаням стремятся;'''.encode(charset), 'plain', charset)
        p2 = MIMEText(
            '''<p>По оживлённым берегам
Громады стройные теснятся
Дворцов и башен; корабли
Толпой со всех концов земли
К богатым пристаням стремятся;</p>'''.encode(charset), 'plain', charset)
        msg1 = MIMEMultipart()
        msg1['Message-ID'] = '<*****@*****.**>'
        msg1.attach(p1)
        msg1.attach(p2)
        s_msg = msg1.as_string()
        msg2 = parse_message(s_msg)
        for part in msg2['parts']:
            if part['payload'] is None:
                continue
            assert isinstance(part['payload'],
                              six.text_type), type(part['payload'])
Exemple #2
0
 def test_html_email_with_images(self):
     msg = MIMEMultipart(
         _subparts=[
             MIMEMultipart(
                 'alternative',
                 _subparts=[
                     MIMEText('This is a test message'),
                     MIMEText('This is a <em>test</em> message', 'html')
                 ])
         ])
     with open(pkg_resources.resource_filename(
             'forgediscussion', 'tests/data/python-logo.png'), 'rb') as fp:
         img = MIMEImage(fp.read())
         img.add_header('Content-Disposition', 'attachment',
                        filename='python-logo.png')
         msg.attach(img)
     self._post_email(
         self.email_address,
         [self.forum.email_address],
         'Test Simple Thread',
         msg)
     r = self.app.get('/p/test/discussion/testforum/')
     assert 'Test Simple Thread' in str(r)
     assert len(r.html.findAll('tr')) == 2
     href = r.html.findAll('tr')[1].find('a')['href']
     r = self.app.get(href)
     assert 'alternate' in str(r)
     assert 'python-logo.png' in str(r)
 def _build_msg(self, stash_name, reason):
     msg = MIMEMultipart()
     msg['From'] = self._from
     msg['To'] = self._to
     msg['Subject'] = '%s %s' % (self._subject_prefix, stash_name)
     msg_text = self._mail_tpl.render(stash_name=stash_name,
                                      reason=reason,
                                      uchiwa_url=self._uchiwa_url)
     msg.attach(MIMEText(msg_text, _charset='utf-8'))
     return msg
Exemple #4
0
def make_multipart_message(*parts):
    msg = MIMEMultipart('related')
    msg.preamble = 'This is a multi-part message in MIME format.'
    alt = MIMEMultipart('alternative')
    msg.attach(alt)
    for part in parts:
        alt.attach(part)
    return msg
Exemple #5
0
    def get_encrypted_message(self, message):
        """Get the encrypted message from the passed payload message.

        Parameters
        ----------

        message : MIMEBase
            The message to encrypt (e.g. as created by :py:func:`get_octed_stream`.
        """

        control = self.get_control_message()
        msg = MIMEMultipart(_subtype='encrypted', _subparts=[control, message])
        msg.set_param('protocol', 'application/pgp-encrypted')
        return msg
Exemple #6
0
    def get_encrypted_message(self, message):
        """Get the encrypted message from the passed payload message.

        Parameters
        ----------

        message : MIMEBase
            The message to encrypt (e.g. as created by :py:func:`get_octed_stream`.
        """

        control = self.get_control_message()
        msg = MIMEMultipart(_subtype='encrypted', _subparts=[control, message])
        msg.set_param('protocol', 'application/pgp-encrypted')
        return msg
Exemple #7
0
    def get_signed_message(self, message, signature):
        """Get a signed MIME message from the passed message and signature messages.

        Parameters
        ----------

        message : MIMEBase
            MIME message that is signed by the signature.
        signature : MIMEBase
            MIME message containing the signature.
        """

        msg = MIMEMultipart(_subtype='signed', _subparts=[message, signature])
        msg.set_param('protocol', 'application/pgp-signature')
        msg.set_param('micalg', 'pgp-sha256')  # TODO: Just the current default
        return msg
Exemple #8
0
def test_send_raw_email_without_source():
    conn = boto3.client("ses", region_name="us-east-1")

    message = MIMEMultipart()
    message["Subject"] = "Test"
    message["From"] = "*****@*****.**"
    message["To"] = "[email protected], [email protected]"

    # Message body
    part = MIMEText("test file attached")
    message.attach(part)

    # Attachment
    part = MIMEText("contents of test file here")
    part.add_header("Content-Disposition", "attachment; filename=test.txt")
    message.attach(part)

    kwargs = dict(RawMessage={"Data": message.as_string()})

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)

    conn.verify_email_identity(EmailAddress="*****@*****.**")
    conn.send_raw_email(**kwargs)

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota["SentLast24Hours"])
    sent_count.should.equal(2)
Exemple #9
0
def test_send_raw_email_without_source():
    conn = boto3.client('ses', region_name='us-east-1')

    message = MIMEMultipart()
    message['Subject'] = 'Test'
    message['From'] = '*****@*****.**'
    message['To'] = '[email protected], [email protected]'

    # Message body
    part = MIMEText('test file attached')
    message.attach(part)

    # Attachment
    part = MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    kwargs = dict(RawMessage={'Data': message.as_string()}, )

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)

    conn.verify_email_identity(EmailAddress="*****@*****.**")
    conn.send_raw_email(**kwargs)

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota['SentLast24Hours'])
    sent_count.should.equal(2)
Exemple #10
0
def test_send_raw_email_without_source():
    conn = boto3.client('ses', region_name='us-east-1')

    message = MIMEMultipart()
    message['Subject'] = 'Test'
    message['From'] = '*****@*****.**'
    message['To'] = '[email protected], [email protected]'

    # Message body
    part = MIMEText('test file attached')
    message.attach(part)

    # Attachment
    part = MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    kwargs = dict(
        RawMessage={'Data': message.as_string()},
    )

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)

    conn.verify_email_identity(EmailAddress="*****@*****.**")
    conn.send_raw_email(**kwargs)

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota['SentLast24Hours'])
    sent_count.should.equal(2)
Exemple #11
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            log.msg(format='Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                    level=log.DEBUG, mailto=to, mailcc=cc, mailsubject=subject, mailattachs=len(attachs))
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Exemple #12
0
    def send(self, sendto='', subject='', attach='', body=' '):
        print('Sending email')
        msg = MIMEMultipart()
        msg["From"] = self.mailfrom
        msg["To"] = sendto
        msg["Subject"] = subject
        msg['Date'] = formatdate(localtime=True)

        #add messagw
        self._print('Attaching msg: %s' % body)
        message = MIMEText('text', "plain")
        message.set_payload(body + '\n')
        msg.attach(message)
        # attach a file
        if attach:
            self._print('Attachment found: %s' % attach)
            part = MIMEBase('application', "octet-stream")
            part.set_payload(open(attach, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % attach)
            msg.attach(part)

        self._print('Creating SMTP')
        server = smtplib.SMTP(self.host, int(self.port))

        if self.tls == 'True' or self.tls == 'true':
            server.starttls()
            self._print('tls started.')
        if self.auth == 'True' or self.auth == 'true':
            try:
                self._print('Logging into to SMTP: %s %s' %
                            (self.user, self.passwd))
                server.login(self.user, self.passwd)  # optional
            except Exception as e:
                print('Failed Login %s' % e)
                sys.exit(0)

        else:
            try:
                self._print('Connecting to SMTP')
                server.connect()
            except Exception as e:
                print('Failed to connect %s' % e)
                sys.exit(0)

        try:
            self._print('Sending mail to: %s' % sendto)
            server.sendmail(self.mailfrom, sendto, msg.as_string())
            print('mail sent.')
            server.close()
        except Exception as e:
            errorMsg = "Unable to send email. Error: %s" % str(e)
Exemple #13
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s '
                         'Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                         {'mailto': to, 'mailcc': cc, 'mailsubject': subject,
                          'mailattachs': len(attachs)})
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Exemple #14
0
 def test_html_email(self):
     msg = MIMEMultipart('alternative',
                         _subparts=[
                             MIMEText('This is a test message'),
                             MIMEText('This is a <em>test</em> message',
                                      'html')
                         ])
     self._post_email(self.email_address, [self.forum.email_address],
                      'Test Simple Thread', msg)
     r = self.app.get('/p/test/discussion/testforum/')
     assert 'Test Simple Thread' in str(r), r
     assert len(r.html.findAll('tr')) == 2
     href = r.html.findAll('tr')[1].find('a')['href']
     r = self.app.get(href)
     assert 'alternate' in str(r)
Exemple #15
0
    def send(self,
             recipients,
             subject,
             text_body,
             html_body=None,
             sender=None,
             **kwargs):
        # type: (List[str], str, str, Optional[str], Optional[str], Any) -> None
        """
        Send email

        Args:
            recipients (List[str]): Email recipient
            subject (str): Email subject
            text_body (str): Plain text email body
            html_body (Optional[str]): HTML email body
            sender (Optional[str]): Email sender. Defaults to global sender.
            **kwargs: See below
            mail_options (list): Mail options (see smtplib documentation)
            rcpt_options (list): Recipient options (see smtplib documentation)

        Returns:
            None

        """
        if sender is None:
            sender = self.sender
        v = validate_email(sender,
                           check_deliverability=False)  # validate and get info
        sender = v['email']  # replace with normalized form
        normalised_recipients = list()
        for recipient in recipients:
            v = validate_email(
                recipient, check_deliverability=True)  # validate and get info
            normalised_recipients.append(
                v['email'])  # replace with normalized form

        if html_body is not None:
            msg = MIMEMultipart('alternative')
            part1 = MIMEText(text_body, 'plain')
            part2 = MIMEText(html_body, 'html')
            msg.attach(part1)
            msg.attach(part2)
        else:
            msg = MIMEText(text_body)
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ', '.join(normalised_recipients)

        # Perform operations via server
        self.connect()
        self.server.sendmail(sender, normalised_recipients, msg.as_string(),
                             **kwargs)
        self.close()
Exemple #16
0
 def send(self,sendto='',
              subject='',
              attach='',
              body=' '): 
     print('Sending email')
     msg = MIMEMultipart()
     msg["From"]    = self.mailfrom
     msg["To"]      = sendto
     msg["Subject"] = subject
     msg['Date']    = formatdate(localtime=True)
     
     #add messagw
     self._print('Attaching msg: %s' %body)
     message = MIMEText('text', "plain")
     message.set_payload(body+'\n')
     msg.attach(message)
     # attach a file
     if attach:
         self._print('Attachment found: %s'% attach)
         part = MIMEBase('application', "octet-stream")
         part.set_payload( open(attach,"rb").read() )
         Encoders.encode_base64(part)
         part.add_header('Content-Disposition', 'attachment; filename="%s"' % attach)
         msg.attach(part)
     
     self._print('Creating SMTP')
     server = smtplib.SMTP(self.host,int(self.port))
     
     if self.tls == 'True' or self.tls == 'true':
         server.starttls()
         self._print('tls started.')
     if self.auth == 'True' or self.auth == 'true':
         try:
             self._print('Logging into to SMTP: %s %s'%(self.user,self.passwd))
             server.login(self.user, self.passwd)  # optional
         except Exception as e:
             print('Failed Login %s'%e)
             sys.exit(0)
         
     else:
         try:
             self._print('Connecting to SMTP')
             server.connect()
         except Exception as e:
             print('Failed to connect %s'%e)
             sys.exit(0)
  
     try:
         self._print('Sending mail to: %s' %sendto)
         server.sendmail(self.mailfrom, sendto, msg.as_string())
         print('mail sent.')
         server.close()
     except Exception as e:
         errorMsg = "Unable to send email. Error: %s" % str(e)
Exemple #17
0
def get_raw_email():
    message = MIMEMultipart()
    message["Subject"] = "Test"
    message["From"] = "*****@*****.**"
    message["To"] = "[email protected], [email protected]"
    # Message body
    part = MIMEText("test file attached")
    message.attach(part)
    # Attachment
    part = MIMEText("contents of test file here")
    part.add_header("Content-Disposition", "attachment; filename=test.txt")
    message.attach(part)
    return message
    def Envoyer(self, message=None):
        # Création du message
        email = MIMEMultipart('alternative')
        # msg['Message-ID'] = make_msgid()

        # if accuseReception == True:
        #     msg['Disposition-Notification-To'] = adresseExpediteur

        email.attach(MIMEText(message.texte_plain.encode('utf-8'), 'plain', 'utf-8'))
        email.attach(MIMEText(message.texte_html.encode('utf-8'), 'html', 'utf-8'))

        tmpmsg = email
        email = MIMEMultipart('mixed')
        email.attach(tmpmsg)

        # Ajout des headers à ce Multipart
        if self.nom_exp in ("", None):
            email['From'] = self.email_exp
        else:
            sender = Header(self.nom_exp, "utf-8")
            sender.append(self.email_exp, "ascii")
            email['From'] = sender  # formataddr((nomadresseExpediteur, adresseExpediteur))
        email['To'] = ";".join(message.destinataires)
        email['Date'] = formatdate(localtime=True)
        email['Subject'] = message.sujet

        message.AttacheImagesIncluses(email)
        message.AttacheFichiersJoints(email)

        try:
            self.connection.sendmail(self.email_exp, message.destinataires, email.as_string())
        except smtplib.SMTPException:
            if not self.fail_silently:
                raise
            return False
        return True
Exemple #19
0
def test_send_raw_email_without_source_or_from():
    conn = boto3.client("ses", region_name="us-east-1")

    message = MIMEMultipart()
    message["Subject"] = "Test"
    message["To"] = "[email protected], [email protected]"

    # Message body
    part = MIMEText("test file attached")
    message.attach(part)
    # Attachment
    part = MIMEText("contents of test file here")
    part.add_header("Content-Disposition", "attachment; filename=test.txt")
    message.attach(part)

    kwargs = dict(RawMessage={"Data": message.as_string()})

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)
Exemple #20
0
def test_send_raw_email_without_source_or_from():
    conn = boto3.client('ses', region_name='us-east-1')

    message = MIMEMultipart()
    message['Subject'] = 'Test'
    message['To'] = '[email protected], [email protected]'

    # Message body
    part = MIMEText('test file attached')
    message.attach(part)
    # Attachment
    part = MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    kwargs = dict(RawMessage={'Data': message.as_string()}, )

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)
Exemple #21
0
    def get_signed_message(self, message, signature):
        """Get a signed MIME message from the passed message and signature messages.

        Parameters
        ----------

        message : MIMEBase
            MIME message that is signed by the signature.
        signature : MIMEBase
            MIME message containing the signature.
        """

        msg = MIMEMultipart(_subtype='signed', _subparts=[message, signature])
        msg.set_param('protocol', 'application/pgp-signature')
        msg.set_param('micalg', 'pgp-sha256')  # TODO: Just the current default
        return msg
Exemple #22
0
def send_error_mail(from_, subject, text, html=None):
    """Sends an email to JuliaBase's administrators.  Normally, it is about an
    error condition but it may be anything.

    :param from_: name (and only the name, not an email address) of the sender;
        this typically is the name of the currently running program
    :param subject: the subject of the message
    :param text: text body of the message
    :param html: optional HTML attachment

    :type from_: unicode
    :type subject: unicode
    :type text: unicode
    :type html: unicode
    """
    cycles = 5
    while cycles:
        try:
            server = smtplib.SMTP(settings.SMTP_SERVER)
            if settings.SMTP_LOGIN:
                server.starttls()
                server.login(settings.SMTP_LOGIN, settings.SMTP_PASSWORD)
            message = MIMEMultipart()
            message["Subject"] = subject
            message["From"] = '"{0}" <{1}>'. \
                format(from_.replace('"', ""), settings.EMAIL_FROM).encode("ascii", "replace")
            message["To"] = settings.EMAIL_TO
            message["Date"] = email.utils.formatdate()
            message.attach(MIMEText(text.encode("utf-8"), _charset="utf-8"))
            if html:
                message.attach(
                    MIMEText(html.encode("utf-8"), "html", _charset="utf-8"))
            server.sendmail(settings.EMAIL_FROM, message["To"],
                            message.as_string())
            server.quit()
        except smtplib.SMTPException:
            pass
        else:
            break
        cycles -= 1
        time.sleep(10)
Exemple #23
0
def sendMail(to,
             subject,
             text,
             files=[],
             server="mail1.psfc.mit.edu",
             ssl=False,
             ssl_port=465,
             ssl_username='',
             ssl_passwd=''):
    assert type(to) == list
    assert type(files) == list
    #    me =  '*****@*****.**'
    me = ssl_username  # '*****@*****.**'
    msg = MIMEMultipart()
    msg['From'] = me
    #    msg['To'] = COMMASPACE.join(['*****@*****.**'])
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    if ssl:
        print((server, ssl_port))
        smtp = smtplib.SMTP_SSL(server, ssl_port)
        smtp.login(ssl_username, ssl_passwd)
    else:
        smtp = smtplib.SMTP(server)
    smtp.sendmail(me, to, msg.as_string())
    smtp.close()
Exemple #24
0
def test_send_raw_email_without_source_or_from():
    conn = boto3.client('ses', region_name='us-east-1')

    message = MIMEMultipart()
    message['Subject'] = 'Test'
    message['To'] = '[email protected], [email protected]'

    # Message body
    part = MIMEText('test file attached')
    message.attach(part)
    # Attachment
    part = MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    kwargs = dict(
        RawMessage={'Data': message.as_string()},
    )

    conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)
Exemple #25
0
def send_mail(to_addr, subj_msg, body_msg, attach_path, serv_addr, serv_port,
              from_addr, passwd):
    """Send an e-mail message using smtplib and email standard python libraries.
    IMPORTANT! Password is stored as plain text! Do NOT use with your personal
    account!

    Args:
        to_addr (str): Recipient address.
        subj_msg (str): Message subject.
        body_msg (str): Message body.
        serv_addr (str): Server's address. Default: <smtp.gmail.com>.
        serv_port (int): Server's port. Default: <587>.
        from_addr (str): Account address. Default: <*****@*****.**>.
        passwd (str): Account password.
    """
    msg = MIMEMultipart()
    if attach_path is not None:
        with open(attach_path, "rb") as fin:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(fin.read())
            encoders.encode_base64(part)
            part.add_header("Content-Disposition",
                            "attachment; filename={0}".format(attach_path))
            msg.attach(part)
    else:
        pass
    msg["From"] = from_addr
    msg["To"] = to_addr
    msg["Subject"] = subj_msg
    msg.attach(MIMEText(body_msg, "plain"))
    server = smtplib.SMTP(serv_addr, serv_port)
    server.starttls()
    server.login(from_addr, passwd)
    text_msg = msg.as_string()
    server.sendmail(from_addr, to_addr, text_msg)
    server.quit
Exemple #26
0
def send_error_mail(from_, subject, text, html=None):
    """Sends an email to JuliaBase's administrators.  Normally, it is about an
    error condition but it may be anything.

    :param from_: name (and only the name, not an email address) of the sender;
        this typically is the name of the currently running program
    :param subject: the subject of the message
    :param text: text body of the message
    :param html: optional HTML attachment

    :type from_: unicode
    :type subject: unicode
    :type text: unicode
    :type html: unicode
    """
    cycles = 5
    while cycles:
        try:
            server = smtplib.SMTP(settings.SMTP_SERVER)
            if settings.SMTP_LOGIN:
                server.starttls()
                server.login(settings.SMTP_LOGIN, settings.SMTP_PASSWORD)
            message = MIMEMultipart()
            message["Subject"] = subject
            message["From"] = '"{0}" <{1}>'. \
                format(from_.replace('"', ""), settings.EMAIL_FROM).encode("ascii", "replace")
            message["To"] = settings.EMAIL_TO
            message["Date"] = email.utils.formatdate()
            message.attach(MIMEText(text.encode("utf-8"), _charset="utf-8"))
            if html:
                message.attach(MIMEText(html.encode("utf-8"), "html", _charset="utf-8"))
            server.sendmail(settings.EMAIL_FROM, message["To"], message.as_string())
            server.quit()
        except smtplib.SMTPException:
            pass
        else:
            break
        cycles -= 1
        time.sleep(10)
Exemple #27
0
def create_message(recipient, image, size, sender, reply_to):
    msg = MIMEMultipart('related')
    msg['from'] = Header(sender, 'utf-8')
    msg['to'] = Header(recipient, 'utf-8')
    msg['subject'] = Header(EMAIL_SUBJECT, 'utf-8')
    if reply_to:
        msg['reply-to'] = Header(reply_to, 'utf-8')

    template = EMAIL_TEMPLATE
    template = template.replace('${width}', str(size[0]))
    template = template.replace('${height}', str(size[1]))

    text = MIMEText(template, 'html', 'utf-8')
    msg.attach(text)

    with open(image, 'rb') as fp:
        img = MIMEImage(fp.read())
    img.add_header('Content-ID', 'image')
    img.add_header('Content-Disposition', 'inline', filename=basename(image))
    msg.attach(img)

    return msg
Exemple #28
0
 def __init__(self, mt, mfrom, mto, _subtype='mixed', boundary=None):
     MIMEMultipart.__init__(self, _subtype, boundary)
     self.mfrom = mfrom
     self.mto = mto
     self.mt = mt
Exemple #29
0
def send_email(xfrom,
               to,
               subject,
               body,
               cc=None,
               bcc=None,
               attachments=None,
               host=None):
    if not has_len(host):
        host = 'localhost'

    outer = MIMEMultipart()

    if has_len(xfrom):
        outer['From'] = xfrom
    elif isinstance(xfrom, (list, tuple)) and len(xfrom) == 2:
        outer['From'] = "%s <%s>" % (Header(unidecoder(xfrom[0]),
                                            'utf-8'), xfrom[1])
        xfrom = xfrom[1]
    else:
        raise ValueError("Invalid e-mail sender. (from: %r)" % xfrom)

    outer['Date'] = formatdate(localtime=True)
    smtp = smtplib.SMTP(host)

    if has_len(to):
        to = [to]

    if isinstance(to, (list, tuple)):
        to = list(to)
        outer['To'] = COMMASPACE.join(list(to))
    else:
        raise ValueError("Invalid e-mail recipients. (to: %r)" % to)

    if has_len(cc):
        cc = [cc]

    if isinstance(cc, (list, tuple)):
        to += list(cc)
        outer['Cc'] = COMMASPACE.join(list(cc))

    if has_len(bcc):
        bcc = [bcc]

    if isinstance(bcc, (list, tuple)):
        to += list(bcc)

    if has_len(subject):
        outer['Subject'] = Header(unidecoder(subject), 'utf-8')

    if has_len(body):
        outer.attach(MIMEText(unidecoder(body), _charset='utf-8'))

    if has_len(attachments):
        attachments = [attachments]

    if attachments:
        if isinstance(attachments, (list, tuple)):
            attachments = dict(
                zip(attachments,
                    len(attachments) * ('application/octet-stream', )))

        for attachment in sorted(iterkeys(attachments)):
            fp = open(attachment, 'rb')
            part = MIMEBase('application', 'octet-stream')
            part.set_type(attachments[attachment])
            filename = os.path.basename(attachment)
            part.set_payload(fp.read())
            fp.close()
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
            outer.attach(part)

    smtp.sendmail(xfrom, to, outer.as_string())
    smtp.quit()
Exemple #30
0
 def __setitem__(self, name, val):
     name, val = forbid_multi_line_headers(name, val)
     MIMEMultipart.__setitem__(self, name, val)
Exemple #31
0
    def Envoyer(self, message=None):
        # Création du message
        email = MIMEMultipart('alternative')
        # msg['Message-ID'] = make_msgid()

        # if accuseReception == True:
        #     msg['Disposition-Notification-To'] = adresseExpediteur

        email.attach(
            MIMEText(message.texte_plain.encode('utf-8'), 'plain', 'utf-8'))
        email.attach(
            MIMEText(message.texte_html.encode('utf-8'), 'html', 'utf-8'))

        tmpmsg = email
        email = MIMEMultipart('mixed')
        email.attach(tmpmsg)

        # Ajout des headers à ce Multipart
        if self.nom_exp in ("", None):
            email['From'] = self.email_exp
        else:
            sender = Header(self.nom_exp, "utf-8")
            sender.append(self.email_exp, "ascii")
            email[
                'From'] = sender  # formataddr((nomadresseExpediteur, adresseExpediteur))
        email['To'] = ";".join(message.destinataires)
        email['Date'] = formatdate(localtime=True)
        email['Subject'] = message.sujet

        message.AttacheImagesIncluses(email)
        message.AttacheFichiersJoints(email)

        try:
            self.connection.sendmail(self.email_exp, message.destinataires,
                                     email.as_string())
        except smtplib.SMTPException:
            if not self.fail_silently:
                raise
            return False
        return True
Exemple #32
0
def rfc3156(message, recipients=None, signers=None, context=None, always_trust=False):
    """
    Parameters
    ----------

    message : :py:class:`email.mime.base.MIMEBase` or str
    context : :py:class:`pygpgme.Context`, optional
        If not set, a new object with default parameters will be created.
    always_trust : bool, optional
        If ``True``, always trust recipient keys.
    """

    if (not signers and not recipients) or context and context.signers:
        raise ValueError("No signers or recipients given.")

    if isinstance(message, six.string_types):
        message = MIMEText(message + '\n\n')
        del message['MIME-Version']

    if recipients is None:
        recipients = []
    elif isinstance(recipients, six.string_types):
        recipients = [recipients]

    if signers is None:
        signers = []
    elif isinstance(signers, six.string_types):
        signers = [signers]

    if context is None:
        context = gpgme.Context()
    context.armor = True

    # signers/recpiients may either be a string or a key from the context
    signers = [(context.get_key(k) if isinstance(k, six.string_types) else k) for k in signers]
    recipients = [context.get_key(k) if isinstance(k, six.string_types) else k for k in recipients]

    if signers:
        context.signers = signers

    input_bytes = six.BytesIO(message.as_bytes())
    output_bytes = six.BytesIO()

    if recipients:  # we have recipients, so we encrypt

        # compute flags passed to encrypt/encrypt_sign
        flags = 0
        if always_trust is True:
            flags |= gpgme.ENCRYPT_ALWAYS_TRUST

        # sign message
        if context.signers:
            context.encrypt_sign(recipients, flags, input_bytes, output_bytes)
        else:
            context.encrypt(recipients, flags, input_bytes, output_bytes)
        output_bytes.seek(0)

        # the control message
        control_msg = MIMEApplication(_data='Version: 1\n', _subtype='pgp-encrypted',
                                      _encoder=encode_noop)
        control_msg.add_header('Content-Description', 'PGP/MIME version identification')
        del control_msg['MIME-Version']

        encrypted = MIMEApplication(_data=output_bytes.getvalue(),
                                    _subtype='octed-stream', name='encrypted.asc',
                                    _encoder=encode_noop)
        encrypted.add_header('Content-Description', 'OpenPGP encrypted message')
        encrypted.add_header('Content-Disposition', 'inline; filename="encrypted.asc"')
        del encrypted['MIME-Version']

        msg = MIMEMultipart(_subtype='pgp-encrypted', _subparts=[control_msg, encrypted])
        msg.set_param('protocol', 'application/pgp-encrypted')
        return msg
    else:  # just signing
        del message['MIME-Version']
        for payload in message.get_payload():
            if isinstance(payload, MIMEBase):
                del payload['MIME-Version']
        message.policy = message.policy.clone(max_line_length=0)

        to_sign = message.as_bytes().replace(b'\n', b'\r\n')
        context.sign(six.BytesIO(to_sign), output_bytes, gpgme.SIG_MODE_DETACH)
        output_bytes.seek(0)
        signature = output_bytes.getvalue()

        sig = MIMEBase(_maintype='application', _subtype='pgp-signature', name='signature.asc')
        sig.set_payload(signature.decode('utf-8'))
        sig.add_header('Content-Description', 'OpenPGP digital signature')
        sig.add_header('Content-Disposition', 'attachment; filename="signature.asc"')
        del sig['MIME-Version']
        del sig['Content-Transfer-Encoding']

        msg = MIMEMultipart(_subtype='signed', _subparts=[message, sig])
        msg.set_param('protocol', 'application/pgp-signature')
        del msg['MIME-Version']

        return msg
Exemple #33
0
 def __setitem__(self, name, val):
     name, val = forbid_multi_line_headers(name, val)
     MIMEMultipart.__setitem__(self, name, val)