Пример #1
0
 def test_japanese_codecs(self):
     eq = self.ndiffAssertEqual
     j = Charset('euc-jp')
     g = Charset('iso-8859-1')
     h = Header('Hello World!')
     jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
     ghello = 'Gr\xfc\xdf Gott!'
     h.append(jhello, j)
     h.append(ghello, g)
     eq(
         h.encode(),
         'Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=\n =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?='
     )
     eq(decode_header(h.encode()),
        [('Hello World!', None),
         ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
         ('Gr\xfc\xdf Gott!', 'iso-8859-1')])
     long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
     h = Header(long, j, header_name='Subject')
     enc = h.encode()
     eq(
         enc,
         '=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=\n =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?='
     )
     eq(h.__unicode__().encode('euc-jp'), long)
     return None
Пример #2
0
    def test_japanese_codecs(self):
        eq = self.ndiffAssertEqual
        j = Charset("euc-jp")
        g = Charset("iso-8859-1")
        h = Header("Hello World!")
        jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
        ghello = 'Gr\xfc\xdf Gott!'
        h.append(jhello, j)
        h.append(ghello, g)
        # BAW: This used to -- and maybe should -- fold the two iso-8859-1
        # chunks into a single encoded word.  However it doesn't violate the
        # standard to have them as two encoded chunks and maybe it's
        # reasonable <wink> for each .append() call to result in a separate
        # encoded word.
        eq(
            h.encode(), """\
Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=
 =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=""")
        eq(decode_header(h.encode()),
           [('Hello World!', None),
            ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
            ('Gr\xfc\xdf Gott!', 'iso-8859-1')])
        int = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
        h = Header(int, j, header_name="Subject")
        # test a very long header
        enc = h.encode()
        # TK: splitting point may differ by codec design and/or Header encoding
        eq(
            enc, """\
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
 =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
        # TK: full decode comparison
        eq(h.__unicode__().encode('euc-jp'), int)
Пример #3
0
def make_to_header(tolist):
    ret = []
    for t in tolist:
        toheader = Header(t[0], 'utf-8')
        toheader.append("<" + t[1] + ">", 'ascii')
        ret.append(toheader)
    return ret
Пример #4
0
def send_mail(tolist, cclist, msg):
    msg['From'] = fromheader
    tos = []
    ccs = []
    list_tomail = []
    list_ccmail = []
    for t in tolist:
        toheader = Header(t[0], 'utf-8')
        toheader.append("<" + t[1] + ">", 'ascii')
        tos.append(str(toheader))
        list_tomail.append(t[1])
    msg['To'] = ';'.join(tos)
    for c in cclist:
        ccheader = Header(t[0], 'utf-8')
        ccheader.append("<" + c[1] + ">", 'ascii')
        ccs.append(str(ccheader))
        list_ccmail.append(c[1])
    msg['CC'] = ';'.join(ccs)
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user, mail_pass)
        server.sendmail(str(fromheader), list_tomail, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False
Пример #5
0
    def test_japanese_codecs(self):
        eq = self.ndiffAssertEqual
        jcode = 'euc-jp'
        gcode = 'iso-8859-1'
        j = Charset(jcode)
        g = Charset(gcode)
        h = Header('Hello World!')
        jhello = str(
            b'\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa',
            jcode)
        ghello = str(b'Gr\xfc\xdf Gott!', gcode)
        h.append(jhello, j)
        h.append(ghello, g)
        eq(
            h.encode(),
            """Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=
 =?iso-8859-1?q?Gr=FC=DF_Gott!?=""")
        eq(decode_header(h.encode()),
           [(b'Hello World! ', None),
            (b'\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
            (b'Gr\xfc\xdf Gott!', gcode)])
        subject_bytes = (
            b'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
        )
        subject = str(subject_bytes, jcode)
        h = Header(subject, j, header_name='Subject')
        enc = h.encode()
        eq(
            enc,
            """=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
 =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
        eq(str(h).encode(jcode), subject_bytes)
Пример #6
0
def sendmail(to_list,host,me,subject,files,content,sysbl):
	logging.basicConfig(level=logging.DEBUG,
		format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
		datefmt='%a, %d %b %Y %H:%M:%S',
		filename='/home/qa/scripts/sendReport/goldpay/GoldpayReportSendmail.log',
		filemode='a+')
	mail_list = to_list.split(';')
	for i in mail_list:
		msg = MIMEMultipart()
		h = Header('Goldpay')
		h.append('<'+me+'>')
		msg['From'] = h
	        msg['To'] = i
		msg['Subject'] = subject
		msg['Date'] = formatdate(localtime=True)
		msg.attach(MIMEText(content,'html','utf8'))
		part = MIMEBase('application', 'octet-stream')
		part.set_payload(open(files, 'rb').read())
		encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(files))
		msg.attach(part)
        	smtp = smtplib.SMTP(host)
		smtp.set_debuglevel(1)
		try:
			smtp.sendmail(me,i,msg.as_string())
			logging.info('%s %s email send success.' % (sysbl,i))
			print 'email send success.'
		except Exception ,e:
			logging.error('%s %s email send failed. %s' % (sysbl,i,e))  
        		print e  
        		print 'email send failed.'
		smtp.quit()
Пример #7
0
    def __get_message(self):
        # 支持附件的邮件
        msg = MIMEMultipart(_charset=self.charset)
        # 添加自定义昵称
        h = Header("123", self.charset)
        h.append('<' + self.email_form + '>', self.charset)
        msg['From'] = h
        msg['From'] = self.email_form
        msg['To'] = self.email_to
        msg['Subject'] = self.email_title

        # 邮件正文内容
        msg.attach(
            MIMEText(self.__get_email_content_html(), 'html', self.charset))
        # 添加附件
        for i in range(len(self.email_enclosure)):
            att1 = MIMEText(open(self.email_enclosure[i], 'rb').read(),
                            'base64',
                            _charset=self.charset)
            att1['Content-Type'] = 'application/octet-stream'
            att1.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '',
                                      os.path.basename(
                                          self.email_enclosure[i])))
            msg.attach(att1)
        return msg
Пример #8
0
def create_and_send_mail_messages(messages):
    if not settings.EMAIL_HOST:
        return

    sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
    sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
    sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))

    try:
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT))
        """
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
                          local_hostname=DNS_NAME.get_fqdn())
        """
        
        if (bool(settings.EMAIL_USE_TLS)):
            connection.ehlo()
            connection.starttls()
            connection.ehlo()

        if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
            connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))

        if sender is None:
            sender = str(settings.DEFAULT_FROM_EMAIL)

        for recipient, subject, html, text, media in messages:
            msgRoot = MIMEMultipart('related')

            msgRoot['Subject'] = Header(subject, 'utf-8')
            msgRoot['From'] = sender

            to = Header(recipient.username, 'utf-8')
            to.append('<%s>' % recipient.email)
            msgRoot['To'] = to

            #msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')

            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)

            msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
            msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))

            for alias, location in media.items():
                fp = open(location, 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', '<'+alias+'>')
                msgRoot.attach(msgImage)

            try:
                connection.sendmail(sender, [recipient.email], msgRoot.as_string())
            except Exception, e:
                logging.error("Couldn't send mail using the sendmail method: %s" % e)

        try:
            connection.quit()
        except socket.sslerror:
            connection.close()
Пример #9
0
def encode_header(key, value):
    """encodes a unicode string as a valid header value

    :param key: the header field this value will be stored in
    :type key: str
    :param value: the value to be encoded
    :type value: unicode
    """
    # handle list of "realname <email>" entries separately
    if key.lower() in ['from', 'to', 'cc', 'bcc']:
        rawentries = value.split(',')
        encodedentries = []
        for entry in rawentries:
            m = re.search('\s*(.*)\s+<(.*\@.*\.\w*)>$', entry)
            if m:  # If a realname part is contained
                name, address = m.groups()
                # try to encode as ascii, if that fails, revert to utf-8
                # name must be a unicode string here
                header = Header(name)
                # append address part encoded as ascii
                header.append('<%s>' % address, charset='ascii')
                encodedentries.append(header.encode())
            else:  # pure email address
                encodedentries.append(entry)
        value = Header(','.join(encodedentries))
    else:
        value = Header(value)
    return value
Пример #10
0
    def render_to_email(self):
        from ..lib.frontend_urls import FrontendUrls
        email_text_part = self.render_to_email_text_part()
        email_html_part = self.render_to_email_html_part()
        if not email_text_part and not email_html_part:
            return ''
        frontendUrls = FrontendUrls(self.first_matching_subscription.discussion)
        msg = email.mime.Multipart.MIMEMultipart('alternative')
        from email.header import Header
        msg['Precedence'] = 'list'
        
        msg['List-ID'] = self.first_matching_subscription.discussion.uri()
        msg['Date'] = email.Utils.formatdate()

        msg['Message-ID'] = "<"+self.event_source_object().message_id+">"
        if self.event_source_object().parent:
            msg['In-Reply-To'] = "<"+self.event_source_object().parent.message_id+">"

        #Archived-At: A direct link to the archived form of an individual email message.
        msg['List-Subscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl()
        msg['List-Unsubscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl()
        msg['Subject'] = Header(self.get_notification_subject(), 'utf-8')

        from_header = Header(self.event_source_object().creator.name, 'utf-8')
        from_header.append(" <" + self.get_from_email_address() + ">", 'ascii')
        msg['From'] = from_header
        msg['To'] = self.get_to_email_address()
        if email_text_part:
            msg.attach(SafeMIMEText(email_text_part.encode('utf-8'), 'plain', 'utf-8'))
        if email_html_part:
            msg.attach(SafeMIMEText(email_html_part.encode('utf-8'), 'html', 'utf-8'))
        
        return msg.as_string()
Пример #11
0
    def send_mail(self, title, content=None, files=None):
        me = Header(self.config.nick_name, 'utf-8')
        me.append("<" + self.config.mail_user + "@" + self.config.mail_postfix + ">", 'ascii')
        #创建一个带附件的实例
        msg = MIMEMultipart()
        #msg = MIMEText(content, _subtype='plain', _charset='gb2312')
        msg['Subject'] = title
        msg['From'] = me
        msg['To'] = ";".join(self.config.mailto_list)
        try:

            text = MIMEText(content, 'plain', 'utf-8')
            msg.attach(text)

            if files!=None:
                for file in files:
                    att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
                    att["Content-Type"] = 'application/octet-stream'
                    att["Content-Disposition"] = 'attachment; filename="'+file+'.txt"'
                    msg.attach(att)

            server = smtplib.SMTP()
            server.connect(self.config.mail_host)
            server.login(self.config.mail_user, self.config.mail_pass)
            print("email sending ....")
            t1 = time.clock()
            server.sendmail(self.config.mail_from, self.config.mailto_list, msg.as_string())
            t2 = time.clock()
            server.close()
            t3 = t2 - t1
            print('success send email ', title, " takes time ", t3)
            return True
        except Exception as e:
            print('failed send email:', e)
            return False
    def test_japanese_codecs(self):
        eq = self.ndiffAssertEqual
        j = Charset("euc-jp")
        g = Charset("iso-8859-1")
        h = Header("Hello World!")
        jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
        ghello = 'Gr\xfc\xdf Gott!'
        h.append(jhello, j)
        h.append(ghello, g)
        # BAW: This used to -- and maybe should -- fold the two iso-8859-1
        # chunks into a single encoded word.  However it doesn't violate the
        # standard to have them as two encoded chunks and maybe it's
        # reasonable <wink> for each .append() call to result in a separate
        # encoded word.
        eq(h.encode(), """\
Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=
 =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=""")
        eq(decode_header(h.encode()),
           [('Hello World!', None),
            ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
            ('Gr\xfc\xdf Gott!', 'iso-8859-1')])
        long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
        h = Header(long, j, header_name="Subject")
        # test a very long header
        enc = h.encode()
        # TK: splitting point may differ by codec design and/or Header encoding
        eq(enc , """\
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
 =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
        # TK: full decode comparison
        eq(h.__unicode__().encode('euc-jp'), long)
Пример #13
0
    def send(self, text, mail_subject):
        # 这里使用SMTP_SSL就是默认使用465端口,如果发送失败,可以使用587
        # smtp = SMTP_SSL(self.mail_info['hostname'])
        smtp = SMTP_SSL('smtp.exmail.qq.com')
        # smtp = SMTP_SSL('smtp.163.com')
        smtp.set_debuglevel(0)
        ''' SMTP 'ehlo' command.
        Hostname to send for this command defaults to the FQDN of the local
        host.
        '''
        self.mail_info['mail_subject'] = f'{mail_subject}接口测试报告'
        smtp.ehlo(self.mail_info['hostname'])
        smtp.login(self.mail_info['username'], self.mail_info['password'])

        # 普通HTML邮件
        # msg = MIMEText(text, 'html', self.mail_info['mail_encoding'])

        # 支持附件的邮件
        msg = MIMEMultipart()
        msg.attach(MIMEText(text, 'html', self.mail_info['mail_encoding']))
        msg['Subject'] = Header(self.mail_info['mail_subject'],
                                self.mail_info['mail_encoding'])
        # msg['from'] = self.mail_info['from']
        h = Header(r'达摩自动化测试', 'utf-8')
        h.append('<' + self.mail_info['from'] + '>', 'ascii')
        msg["from"] = h

        # logger.debug( self.mail_info )
        # logger_yzy.debug(text)
        msg['to'] = ','.join(self.mail_info['to'])
        receive = self.mail_info['to']

        # 抄送
        if self.mail_info['cc'] is None or self.mail_info['cc'][0].__len__(
        ) < 1:
            logger.info('没有抄送')
        else:
            msg['cc'] = ','.join(self.mail_info['cc'])
            receive += self.mail_info['cc']

        # 添加附件
        for i in range(len(self.mail_info['filepaths'])):
            att1 = MIMEText(
                open(self.mail_info['filepaths'][i], 'rb').read(), 'base64',
                'utf-8')
            att1['Content-Type'] = 'application/octet-stream'
            # att1['Content-Disposition'] = 'attachment; filename= "'+self.mail_info['filenames'][i]+'"'
            att1.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '',
                                      self.mail_info['filenames'][i]))
            msg.attach(att1)

        try:
            smtp.sendmail(self.mail_info['from'], receive, msg.as_string())
            smtp.quit()
            logger.info('邮件发送:--> 成功(雅讯邮箱)')
        except Exception as e:
            logger.info('邮件发送失败:')
            logger.info(e)
Пример #14
0
def send_mail(msg_to: str, message: str):
    msg_from = '@qq.com'  # 发送方邮箱地址。
    password = ''  # 发送方QQ邮箱授权码,不是QQ邮箱密码。
    # msg_to = ''  # 收件人邮箱地址。

    subject = "体温填报"  # 主题。
    content = message  # 邮件正文内容。
    msg = MIMEText(content, 'plain', 'utf-8')

    msg_header = Header('汐离、', 'utf-8')
    msg_header.append('<@qq.com>', 'ascii')

    msg['Subject'] = subject
    msg['From'] = msg_header
    msg['To'] = msg_to

    try:
        client = smtplib.SMTP_SSL('smtp.qq.com', smtplib.SMTP_SSL_PORT)
        print("连接到邮件服务器成功")

        client.login(msg_from, password)
        print("登录成功")

        client.sendmail(msg_from, msg_to, msg.as_string())
        print("发送成功")
    except smtplib.SMTPException as e:
        print("发送邮件异常")
    finally:
        client.quit()
Пример #15
0
def sendmail(to_list,host,me,subject,files,content,sysbl):
	logging.basicConfig(level=logging.DEBUG,
		format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
		datefmt='%a, %d %b %Y %H:%M:%S',
		filename='/home/qa/scripts/sendReport/goldpay/GoldpayReportSendmail.log',
		filemode='a+')
	mail_list = to_list.split(';')
	for i in mail_list:
		msg = MIMEMultipart()
		h = Header('Goldpay')
		h.append('<'+me+'>')
		msg['From'] = h
	        msg['To'] = i
		msg['Subject'] = subject
		msg['Date'] = formatdate(localtime=True)
		msg.attach(MIMEText(content,'html','utf8'))
		part = MIMEBase('application', 'octet-stream')
		part.set_payload(open(files, 'rb').read())
		encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(files))
		msg.attach(part)
        	smtp = smtplib.SMTP(host)
		smtp.set_debuglevel(1)
		try:
			smtp.sendmail(me,i,msg.as_string())
			logging.info('%s %s email send success.' % (sysbl,i))
			print 'email send success.'
		except Exception ,e:
			logging.error('%s %s email send failed. %s' % (sysbl,i,e))  
        		print e  
        		print 'email send failed.'
		smtp.quit()
Пример #16
0
def compose_email(to_mailbox, from_mailbox, subject, content,
                 to_display_name = None, from_display_name = None,
                 reply_to_mailbox = None, reply_to_display_name = None,
                 sender_mailbox = None, sender_display_name = None,
                 id = None, orig_date = None, **kw):
    
    # Constructs the email and adds the content
    msg = MIMEText(content, _charset='utf-8')

    # Add mandatory headers
    msg['Message-Id'] = email.utils.make_msgid(str(id)) if id else email.utils.make_msgid()
    msg['Date'] = _formatdate(orig_date if orig_date else datetime.datetime.now(pytz.utc))
    msg['To'] = _formataddr(to_mailbox, to_display_name, header_name="To")
    msg['From'] = _formataddr(from_mailbox, from_display_name, header_name="From")

    subject_header = Header(header_name="Subject")
    subject_header.append(remove_control_chars(subject))
    msg['Subject'] = subject_header

    # Add "Reply-To" if given
    if reply_to_mailbox:
        msg['Reply-To'] = _formataddr(reply_to_mailbox, reply_to_display_name, 
                                      header_name="Reply-To")

    # Add "Sender" if given
    if sender_mailbox:
        msg['Sender'] = _formataddr(sender_mailbox, sender_display_name, header_name="Sender")

    return msg
Пример #17
0
def send(sub, content):

    me = u"%s<%s@%s>" % (mail_alias, mail_user, mail_postfix)
    mail_from = "<%s@%s>" % (mail_user, mail_postfix)

    header = Header(mail_alias, 'utf-8')
    header.append(mail_from, "ascii")

    msg = MIMEText(content, _subtype='plain', _charset='gb2312')
    msg['Subject'] = sub
    msg["From"] = header

    """
    msg['To']字符串"[email protected], [email protected]"
    sendmail参数mail_to为list
    """
    msg['To'] = mail_to

    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user,mail_pass)
        server.sendmail(me, mail_to_list, msg.as_string())
        server.close()
    except Exception as e:
        #print(e)
        return False
    return True
Пример #18
0
 def test_decode_header_multipart(self):
     """
     Two part header: iso-8859-1 and utf-8
     """
     h = Header(b'M\xfcnchen', 'iso-8859-1')
     h.append(b' M\xc3\xbcnchen', 'utf-8')
     header_text = decode_header(h)
     self.assertEqual('München München', header_text)
Пример #19
0
def create_and_send_mail_messages(messages):
    if not settings.EMAIL_HOST:
        return

    sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
    sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
    sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))

    reply_to = unicode(settings.DEFAULT_REPLY_TO_EMAIL)

    try:
        connection = None

        if sender is None:
            sender = str(settings.DEFAULT_FROM_EMAIL)

        for recipient, subject, html, text, media in messages:
            if connection is None:
                connection = create_connection()

            msgRoot = MIMEMultipart('related')

            msgRoot['Subject'] = Header(subject, 'utf-8')
            msgRoot['From'] = sender

            to = Header(recipient.username, 'utf-8')
            to.append('<%s>' % recipient.email)
            msgRoot['To'] = to

            if reply_to:
                msgRoot['Reply-To'] = reply_to

            msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')

            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)

            msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
            msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))

            for alias, location in media.items():
                fp = open(location, 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', '<'+alias+'>')
                msgRoot.attach(msgImage)

            try:
                connection.sendmail(sender, [recipient.email], msgRoot.as_string())
            except SMTPRecipientsRefused, e:
                logging.error("Email address not accepted.  Exception: %s" % e)
            except Exception, e:
                logging.error("Couldn't send mail using the sendmail method: %s" % e)
                try:
                    connection.quit()
                except Exception, e:
                    logging.error(e)
Пример #20
0
    def send_email_confirmed(self):
        # construct mail ...
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:

            settings = PlistSettings.objects.all()[0]
            fr = settings.mailSender

            to = self.customer.email

            text = "Hallo "
            text += "%s" % (self.customer.name)
            text += ",\n\n"
            text += u"du hast in der Pünte %.2f Euro Schulden.\n" % (self.customer.depts)
            text += u"Bitte bezahle diese bei deinem nächsten Besuch.\n"
            text += u"Viele Grüße, dein Püntenteam"
            # comment these two lines out to remove signature from mail
            # command = u"echo '%s' | gpg2 --clearsign --passphrase %s --batch -u 'Pünte OSS' --yes -o -"%(text, config.PASSPHRASE)
            # text = os.popen(command.encode('utf-8')).read()
            # msg = Message()
            msg = MIMEText(text, "plain", _charset="UTF-8")
            # msg.set_payload(text)
            msg["Subject"] = Header("[Pünte]Zahlungserinnerung", "utf8")
            fromhdr = Header(u"Pünte", "utf8")
            fromhdr.append(u"<%s>" % fr, "ascii")
            msg["From"] = fromhdr
            tohdr = Header("%s" % self.customer.name, "utf8")
            tohdr.append("<%s>" % (self.customer.email), "ascii")
            msg["To"] = tohdr
            date = datetime.now()
            msg["Date"] = date.strftime("%a, %d %b %Y %H:%M:%S")
            # ... and try to send it
            #
            print "connecting..."
            server = str(settings.mailServer.partition(":")[0])
            port = int(settings.mailServer.partition(":")[2])
            print server, port
            try:
                s = smtplib.SMTP(server, port)
                s.ehlo()
                s.starttls()
                print "logging in..."
                s.login(fr, str(settings.mailPassword))
                print "sending..."
                s.sendmail(fr, self.customer.email, msg.as_string())
                self.msg_box.setText("Erinnerungsmail an %s verschickt" % (self.customer.name))
                s.quit()
                print "connection terminated"
            except Exception, e:
                print e
                s.quit()
                self.msg_box.setText("Fehler beim Versenden")
        finally:
            self.confirm_dialog.hide()
            QApplication.restoreOverrideCursor()
        self.msg_box.show()
Пример #21
0
    def send(self, text):
        # 这里使用SMTP_SSL就是默认使用465端口,如果发送失败,可以使用587
        smtp = SMTP_SSL(self.mail_info['hostname'])
        smtp.set_debuglevel(0)
        ''' SMTP 'ehlo' command.
        Hostname to send for this command defaults to the FQDN of the local
        host.
        '''
        smtp.ehlo(self.mail_info['hostname'])
        smtp.login(self.mail_info['username'], self.mail_info['password'])

        # 普通HTML邮件
        # msg = MIMEText(text, 'html', self.mail_info['mail_encoding'])

        # 支持附件的邮件
        msg = MIMEMultipart()
        msg.attach(MIMEText(text, 'html', self.mail_info['mail_encoding']))

        msg['Subject'] = Header(self.mail_info['mail_subject'],
                                self.mail_info['mail_encoding'])
        # msg['from'] = self.mail_info['from']

        h = Header('老will', 'utf-8')
        h.append('<' + self.mail_info['from'] + '>', 'utf-8')
        msg["From"] = h

        logger.debug(self.mail_info)
        logger.debug(text)
        msg['to'] = ','.join(self.mail_info['to'])
        receive = self.mail_info['to']
        # 处理抄送列表为空的情况
        if self.mail_info['cc'] is None or self.mail_info['cc'][0] == '':
            # 没有抄送列表的时候,就不抄送
            pass
        else:
            msg['cc'] = ','.join(self.mail_info['cc'])
            receive += self.mail_info['cc']

        # 添加附件
        for i in range(len(self.mail_info['filepaths'])):
            att1 = MIMEText(
                open(self.mail_info['filepaths'][i], 'rb').read(), 'base64',
                'utf-8')
            att1['Content-Type'] = 'application/octet-stream'
            att1[
                'Content-Disposition'] = 'attachment; filename= "' + self.mail_info[
                    'filenames'][i] + '"'
            msg.attach(att1)

        try:
            smtp.sendmail(self.mail_info['from'], receive, msg.as_string())
            smtp.quit()
            logger.info('邮件发送成功')
        except Exception as e:
            logger.error('邮件发送失败:')
            logger.exception(e)
Пример #22
0
    def utf8_mime_addr(cls, m):
        dnm = m.group(1).strip()
        if not dnm:
            return m.group(2)

        from email.header import Header, UTF8
        h = Header()
        h.append(dnm, UTF8)
        h.append(f' <{m.group(2)}>')
        return h.encode()
Пример #23
0
 def get_header(self, name, value=None):
     """
     Return a single email header
     :param name: the header name
     :return: Header instance
     """
     _header = Header(header_name=name, charset=self.charset)
     if value:
         _header.append(value)
     return _header
Пример #24
0
 def receivedHeader(self, helo, origin, rcpt):
     recv = "from {hello0} [{hello1}] message to {rcpts}; {date}"
     rcpts = ",".join([str(r.dest) for r in rcpt])
     date = utils.format_datetime(datetime.datetime.now())
     hh = Header("Received")
     hh.append(
         recv.format(hello0=helo[0].decode('ascii'),
                     hello1=helo[1].decode('ascii'),
                     rcpts=rcpts,
                     date=date).encode('ascii'))
     return hh.encode().encode('ascii')
Пример #25
0
def send_message(from_,
                 to,
                 subject,
                 text,
                 html,
                 attachments,
                 settings,
                 from_name='SMART Direct'):
    '''Generates and sends out a proper multipart email message
       with the supplied parameters over SMPTS (secure SMTP)
    '''

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    # Generate a friendly "from" header
    from_header = Header(charset='us-ascii', header_name='from')
    formated_addr = formataddr((from_name, from_))
    from_header.append(formated_addr, charset='us-ascii')

    # Create the enclosing (outer) message
    outer = MIMEMultipart('mixed')
    outer['To'] = to
    outer['From'] = from_header
    outer['Subject'] = subject
    #outer.add_header('Reply-To', from_)
    outer.preamble = 'This is a multi-part message in MIME format.'

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    outer2 = MIMEMultipart('alternative')
    outer2.attach(part1)
    outer2.attach(part2)
    outer.attach(outer2)

    # Process the attachments and add them to the message
    for a in attachments:
        ctype = a['mime']
        maintype, subtype = ctype.split('/', 1)
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(a['file_buffer'].getvalue())
        encoders.encode_base64(msg)
        msg.add_header('Content-Disposition', 'attachment', filename=a['name'])
        outer.attach(msg)

    # Send the message via SMTPS
    user = settings['user']
    password = settings['password']
    s = smtplib.SMTP_SSL(settings['host'])
    s.login(user, password)
    s.sendmail(from_, [to], outer.as_string())
    s.close()
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText): 
        strFrom = fromAdd
        #if isinstance(toAdd,list) :
        #    strTo = ', '.join(toAdd) 
        #else :
        strTo = toAdd
        server = authInfo.get('server')
        user = authInfo.get('user')
        passwd = authInfo.get('password') 
        if not (server and user and passwd) :
                print 'incomplete login info, exit now'
                return 
        # 设定root信息
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        h = Header('Etekcitizen','utf-8')
        h.append('<'+strFrom+'>', 'ascii')
        msgRoot['From'] = h
        msgRoot['To'] = strTo
        print strTo , user , server
        msgRoot.preamble = 'This is a multi-part message in MIME format.' 
        # Encapsulate the plain and HTML versions of the message body in an
        #'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative) 
        #设定纯文本信息
        #msgText = MIMEText(plainText, 'plain', 'utf-8')
        #msgAlternative.attach(msgText) 
        #设定HTML信息
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText) 
        #设定内置图片信息
        #fp = open('test.jpg', 'rb')
        #msgImage = MIMEImage(fp.read())
        #fp.close()
        #msgImage.add_header('Content-ID', '<image1>')
        #msgRoot.attach(msgImage) 
        try :
            #发送邮件
            smtp = smtplib.SMTP()
            #设定调试级别,依情况而定
            smtp.set_debuglevel(0)
            smtp.connect(server)
            smtp.login(user, passwd)
            smtp.sendmail(strFrom, strTo, msgRoot.as_string())
            smtp.quit()
            return True;
        except Exception, e:
            file = open('error.txt','a')
            file.write(time.strftime('%Y-%m-%d %H:%M:%S') + str(e))
            file.write('\n-------------\n')
            file.close()
            return False;
Пример #27
0
    def send(self, text):
        smtp = SMTP_SSL(self.mail_info['hostname'])
        smtp.set_debuglevel(0)
        ''' SMTP 'ehlo' command.
        Hostname to send for this command defaults to the FQDN of the local
        host.
        '''
        smtp.ehlo(self.mail_info['hostname'])
        smtp.login(self.mail_info['username'], self.mail_info['password'])

        # 普通HTML邮件
        # msg = MIMEText(text, 'html', self.mail_info['mail_encoding'])

        # 支持附件的邮件
        msg = MIMEMultipart()
        msg.attach(MIMEText(text, 'html', self.mail_info['mail_encoding']))
        msg['Subject'] = Header(self.mail_info['mail_subject'],
                                self.mail_info['mail_encoding'])
        # msg['from'] = self.mail_info['from']
        # 添加自定义昵称
        h = Header(self.mail_info['mailnick'], 'utf-8')
        h.append('<' + self.mail_info['from'] + '>', 'ascii')
        msg["from"] = h

        # logger.debug(self.mail_info)
        # logger.debug(text)
        msg['to'] = ','.join(self.mail_info['to'])
        msg['cc'] = ','.join(self.mail_info['cc'])
        receive = self.mail_info['to']
        receive += self.mail_info['cc']

        # 添加附件
        for i in range(len(self.mail_info['filepaths'])):
            att1 = MIMEText(
                open(self.mail_info['filepaths'][i], 'rb').read(), 'base64',
                'utf-8')
            att1['Content-Type'] = 'application/octet-stream'
            att1.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '',
                                      self.mail_info['filenames'][i]))

            msg.attach(att1)

        for i in range(3):
            try:
                smtp.sendmail(self.mail_info['from'], receive, msg.as_string())
                smtp.quit()
                logger.info('邮件发送成功')
                break
            except Exception as e:
                logger.error(f'邮件发送失败第{i}次,重试发送,达到3次后不再重试:')
                logger.exception(e)
Пример #28
0
    def enc_addresses(addr_list):
        addr = []

        enc_addr = getaddresses(addr_list)

        for a in enc_addr:
            h = Header()
            h.append(a[0])
            h.append('<' + a[1] + '>')
            addr.append(h.encode())

        return ','.join(addr)
Пример #29
0
def write_patch_file(filename, commit_info, diff):
    """Write patch file"""
    if not diff:
        gbp.log.debug("I won't generate empty diff %s" % filename)
        return None
    try:
        with open(filename, 'wb') as patch:
            msg = Message()
            charset = Charset('utf-8')
            charset.body_encoding = None
            charset.header_encoding = QP

            # Write headers
            name = commit_info['author']['name']
            email = commit_info['author']['email']
            # Git compat: put name in quotes if special characters found
            if re.search("[,.@()\[\]\\\:;]", name):
                name = '"%s"' % name
            from_header = Header(header_name='from')
            try:
                from_header.append(name, 'us-ascii')
            except UnicodeDecodeError:
                from_header.append(name, charset)
            from_header.append('<%s>' % email)
            msg['From'] = from_header
            date = commit_info['author'].datetime
            datestr = date.strftime('%a, %-d %b %Y %H:%M:%S %z')
            msg['Date'] = Header(datestr, 'us-ascii', 'date')
            subject_header = Header(header_name='subject')
            try:
                subject_header.append(commit_info['subject'], 'us-ascii')
            except UnicodeDecodeError:
                subject_header.append(commit_info['subject'], charset)
            msg['Subject'] = subject_header
            # Write message body
            if commit_info['body']:
                # Strip extra linefeeds
                body = commit_info['body'].rstrip() + '\n'
                try:
                    msg.set_payload(body.encode('us-ascii'))
                except (UnicodeEncodeError):
                    msg.set_payload(body, charset)
            patch.write(
                msg.as_string(unixfrom=False, maxheaderlen=77).encode('utf-8'))

            # Write diff
            patch.write(b'---\n')
            patch.write(diff)
    except IOError as err:
        raise GbpError('Unable to create patch file: %s' % err)
    return filename
Пример #30
0
def sendMail_HTML(server, user, password, From, To, subject, body, file_list, reply_to, encode, bLogin=False):

    server = smtplib.SMTP(server)
    server.docmd("EHLO server")

    if bLogin:
        server.starttls()
        server.login(user, password)

    main_msg = email.MIMEMultipart.MIMEMultipart()

    # text_msg = email.MIMEText.MIMEText(body)
    text_msg = email.MIMEText.MIMEText(body, "html", encode)

    main_msg.attach(text_msg)

    contype = "application/octet-stream"
    maintype, subtype = contype.split("/", 1)

    for file_name in file_list:
        try:
            data = open(file_name, "rb")
            file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
            file_msg.set_payload(data.read())
            data.close()
            email.Encoders.encode_base64(file_msg)

            basename = os.path.basename(file_name)
            file_msg.add_header("Content-Disposition", "attachment", filename=basename)
            main_msg.attach(file_msg)
        except:
            pass

    frmHeader = Header("server status report", encode)
    frmHeader.append("<" + From + ">", "ascii")
    main_msg["From"] = frmHeader
    main_msg["To"] = To
    main_msg["Reply-To"] = reply_to
    main_msg["Subject"] = Header(subject, encode)
    main_msg["Date"] = email.Utils.formatdate()

    fullText = main_msg.as_string()

    # 用smtp发送邮件
    try:
        result = server.sendmail(From, To, fullText)
        return result
    finally:
        server.quit()

    return None
Пример #31
0
def write_patch_file(filename, commit_info, diff):
    """Write patch file"""
    if not diff:
        gbp.log.debug("I won't generate empty diff %s" % filename)
        return None
    try:
        with open(filename, 'wb') as patch:
            msg = Message()
            charset = Charset('utf-8')
            charset.body_encoding = None
            charset.header_encoding = QP

            # Write headers
            name = commit_info['author']['name']
            email = commit_info['author']['email']
            # Git compat: put name in quotes if special characters found
            if re.search(r'[,.@()\[\]\\\:;]', name):
                name = '"%s"' % name
            from_header = Header(header_name='from')
            try:
                from_header.append(name, 'us-ascii')
            except UnicodeDecodeError:
                from_header.append(name, charset)
            from_header.append('<%s>' % email)
            msg['From'] = from_header
            date = commit_info['author'].datetime
            datestr = date.strftime('%a, %-d %b %Y %H:%M:%S %z')
            msg['Date'] = Header(datestr, 'us-ascii', 'date')
            subject_header = Header(header_name='subject')
            try:
                subject_header.append(commit_info['subject'], 'us-ascii')
            except UnicodeDecodeError:
                subject_header.append(commit_info['subject'], charset)
            msg['Subject'] = subject_header
            # Write message body
            if commit_info['body']:
                # Strip extra linefeeds
                body = commit_info['body'].rstrip() + '\n'
                try:
                    msg.set_payload(body.encode('us-ascii'))
                except (UnicodeEncodeError):
                    msg.set_payload(body, charset)
            policy = Compat32(max_line_length=77)
            patch.write(msg.as_bytes(unixfrom=False, policy=policy))

            # Write diff
            patch.write(b'---\n')
            patch.write(diff)
    except IOError as err:
        raise GbpError('Unable to create patch file: %s' % err)
    return filename
Пример #32
0
def split_header(fullline):
    result = re.sub(ur'\?=.+?=\?', '?=\n=?', fullline)
    result = result.split("\n")
    header = Header()
    for line in result:
        header.append(line)
    default_charset = 'ASCII'
    dh = decode_header(header)
    try:
        line_decoded = ''.join(
            [unicode(t[0], t[1] or default_charset) for t in dh])
        return line_decoded
    except BaseException:
        return fullline
Пример #33
0
    def get_emails_header(self, attr):
        c = Charset(self.charset)
        c.header_encoding = QP
        c.body_encoding = 0
        r = Charset(self.charset)
        r.header_encoding = 0
        r.body_encoding = 0

        h = Header()
        self.normalize_email_list(attr)
        emails = self.__getattribute__(attr)

        for i in range(len(emails)):
            name, email = emails[i]

            if i:
                h.append(',', r)

            if name:
                name = name.encode(self.charset, 'xmlcharrefreplace')
                h.append(name, r if is7bit(name) else c)
                h.append('<%s>' % email, r)
            else:
                h.append(email, r)

        return h
Пример #34
0
    def get_emails_header(self, attr):
        c = Charset(self.charset)
        c.header_encoding = QP
        c.body_encoding = 0
        r = Charset(self.charset)
        r.header_encoding = 0
        r.body_encoding = 0

        h = Header()
        self.normalize_email_list(attr)
        emails = self.__getattribute__(attr)

        for i in range(len(emails)):
            name, email = emails[i]

            if i:
                h.append(',', r)

            if name:
                name = name.encode(self.charset, 'xmlcharrefreplace')
                h.append(name, r if is7bit(name) else c)
                h.append('<%s>' % email, r)
            else:
                h.append(email, r)
        return h
Пример #35
0
def send_email(subject, html):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    sender = Header('成绩', 'utf-8')
    sender.append('<%s>' % smtp_username, 'ascii')
    msg['From'] = sender
    msg['To'] = smtp_to
    msg.attach(MIMEText(html, 'html', 'utf-8'))
    if smtp_ssl:
        s = smtplib.SMTP_SSL(smtp_server)
    else:
        s = smtplib.SMTP(smtp_server)
    s.login(smtp_username, smtp_password)
    s.sendmail(smtp_username, smtp_to, msg.as_string())
    s.quit()
Пример #36
0
    def send_invitation(self, invitation, email, inviter, comment):
        """Send a invitation email to a user
        """

        properties = getUtility(IPropertiesTool)
        # prepare from address for header
        header_from = Header(properties.email_from_name,
                             'utf-8')
        header_from.append(u'<%s>' % properties.email_from_address.
                           decode('utf-8'),
                           'utf-8')
        # get subject
        header_subject = Header(unicode(self.get_subject()), 'utf-8')

        # prepare comment
        pttool = getToolByName(self.context, 'portal_transforms')
        html_comment = comment and pttool('text_to_html', comment) or ''

        # prepare options
        options = {
            'invitation': invitation,
            'email': email,
            'inviter': inviter,
            'inviter_name': inviter.getProperty('fullname',
                                                False) or inviter.getId(),
            'text_comment': comment,
            'html_comment': html_comment,
            'link_url': self.get_url(invitation),
            'site_title': self.context.portal_url.getPortalObject().Title(),
            }

        # get the body views
        html_view = self.context.unrestrictedTraverse('@@invitation_mail_html')
        text_view = self.context.unrestrictedTraverse('@@invitation_mail_text')
        # make the mail
        msg = MIMEMultipart('alternative')
        msg['Subject'] = header_subject
        msg['From'] = str(header_from)
        msg['To'] = email

        # render and embedd html / text
        text_body = text_view(**options).encode('utf-8')
        msg.attach(MIMEText(text_body, 'plain', 'utf-8'))
        html_body = html_view(**options).encode('utf-8')
        msg.attach(MIMEText(html_body, 'html', 'utf-8'))
        # send the mail
        mh = getToolByName(self.context, 'MailHost')
        mh.send(msg)
Пример #37
0
def send_message (from_, to, subject, text, html, attachments, settings, from_name = 'SMART Direct'): 
    '''Generates and sends out a proper multipart email message
       with the supplied parameters over SMPTS (secure SMTP)
    '''

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    # Generate a friendly "from" header
    from_header = Header (charset='us-ascii', header_name='from')
    formated_addr = formataddr ((from_name, from_))
    from_header.append (formated_addr, charset='us-ascii')
    
    # Create the enclosing (outer) message
    outer = MIMEMultipart('mixed')
    outer['To'] = to
    outer['From'] = from_header
    outer['Subject'] = subject
    #outer.add_header('Reply-To', from_)
    outer.preamble = 'This is a multi-part message in MIME format.'

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    outer2 = MIMEMultipart('alternative')
    outer2.attach(part1)
    outer2.attach(part2)
    outer.attach(outer2)
    
    # Process the attachments and add them to the message
    for a in attachments:
        ctype = a['mime']
        maintype, subtype = ctype.split('/', 1)
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(a['file_buffer'].getvalue())
        encoders.encode_base64(msg)
        msg.add_header('Content-Disposition', 'attachment', filename=a['name'])
        outer.attach(msg)
    
    # Send the message via SMTPS
    user = settings['user']
    password = settings['password']
    s = smtplib.SMTP_SSL(settings['host'])
    s.login(user, password)
    s.sendmail(from_, [to], outer.as_string())
    s.close()
Пример #38
0
def post(fileName, **conf):
    '''post email'''
    date = datetime.now().strftime('%Y-%m-%d')
    dir = os.path.dirname(fileName)
    content = ''

    if 'from_email' not in conf or not conf['from_email']:
        print Fore.RED + 'from_email is required'
        return

    if 'to_email' not in conf or not conf['to_email']:
        print Fore.RED + 'to_email is required'
        return

    if os.path.exists(fileName):
        with open(fileName, 'r') as r:
            content = r.read()

    if len(content) > 0:
        content = mistune.markdown(content, escape=True, hard_wrap=True)
        hFrom = Header(conf['sender_nickname'], 'utf-8')
        hFrom.append('<%s>\r\n' % conf['from_email'], 'utf-8')

        TO_ADDR = conf['to_email'].split(',')
        CC_ADDR = conf['cc'].split(',')

        hTo = ', '.join(TO_ADDR)
        hCc = ', '.join(CC_ADDR)

        msg = MIMEText(content, 'html', 'utf-8')
        msg['Subject'] = u'工作周报 %s\r\n' % date
        msg['From'] = hFrom
        msg['To'] = hTo
        msg['Cc'] = hCc

        smtp = smtplib.SMTP(conf['host'])
        smtp.login(conf['from_email'], conf['password'])
        smtp.sendmail(conf['from_email'],
                      TO_ADDR + CC_ADDR,
                      msg.as_string())
        smtp.close()

        os.rename(fileName, os.path.join(dir, '%s.rp' % date))

        print Fore.GREEN + 'Send successfully'
    else:
        print 'Nothing to send'
Пример #39
0
def _send_mail_by_ses(messages):
    if not settings.EMAIL_HOST:
        return

    if len(messages) == 0:
        return

    is_invitate=False
    sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
    sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
    sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))

    try:
        index = 0
        connection = None
        for recipient, subject, html, text, media in messages:

            if sender is None:
                sender = str(settings.DEFAULT_FROM_EMAIL)
                
            if hasattr(messages[0][0],"type") and messages[0][0].type == "invitation":
                is_invitate=True

            print ">>>",recipient.email," ",index
            index += 1

            msg = EmailMultiAlternatives(subject, from_email=sender,to=[recipient.email])
            msg.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')

            msgAlternative = MIMEMultipart('alternative')
            msg.attach(msgAlternative)

            msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
            msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))
            for alias, location in media.items():
                fp = open(location, 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', '<'+alias+'>')
                msg.attach(msgImage)

            try:
                msg.send()
            except Exception, e:
                logging.error("Couldn't send mail using the sendmail method: %s" % e)
    except Exception, e:
        logging.error('Email sending has failed: %s' % e)
Пример #40
0
 def test_japanese_codecs(self):
     eq = self.ndiffAssertEqual
     j = Charset('euc-jp')
     g = Charset('iso-8859-1')
     h = Header('Hello World!')
     jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
     ghello = 'Gr\xfc\xdf Gott!'
     h.append(jhello, j)
     h.append(ghello, g)
     eq(h.encode(), 'Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=\n =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=')
     eq(decode_header(h.encode()), [('Hello World!', None), ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')])
     long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
     h = Header(long, j, header_name='Subject')
     enc = h.encode()
     eq(enc, '=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=\n =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=')
     eq(h.__unicode__().encode('euc-jp'), long)
     return None
Пример #41
0
def _encode_address_string(text, charset):
    """Split the email into parts and use header encoding on the name
    part if needed. We do this because the actual addresses need to be
    ASCII with no encoding for most SMTP servers, but the non-address
    parts should be encoded appropriately."""
    header = Header()
    name, addr = parseaddr(text)
    if isinstance(name, six.binary_type):
        try:
            name.decode('us-ascii')
        except UnicodeDecodeError:
            if charset:
                charset = Charset(charset)
                name = charset.header_encode(name)
    # We again replace rather than raise an error or pass an 8bit string
    header.append(formataddr((name, addr)), errors='replace')
    return header
Пример #42
0
def sendEmail(subject, message, email_from, to):
    HOST = settings.EMAIL_HOST
    msg = MIMEText(message, 'html', "utf-8")
    msg['Subject'] = subject

    h = Header('浮文掠影', 'utf-8')
    h.append('<{}>'.format(email_from), 'ascii')

    msg['From'] = h
    msg['To'] = ",".join(to)

    server = smtplib.SMTP_SSL()
    server.connect(HOST, 465)
    server.login(email_from, settings.EMAIL_HOST_PASSWORD)
    server.sendmail(email_from, to, msg.as_string())
    server.quit()
    return True
Пример #43
0
    def render_to_email(self):
        from ..lib.frontend_urls import FrontendUrls
        email_text_part = self.render_to_email_text_part()
        email_html_part = self.render_to_email_html_part()
        if not email_text_part and not email_html_part:
            return ''
        frontendUrls = FrontendUrls(
            self.first_matching_subscription.discussion)
        msg = email.mime.Multipart.MIMEMultipart('alternative')
        from email.header import Header
        msg['Precedence'] = 'list'

        msg['List-ID'] = self.first_matching_subscription.discussion.uri()
        msg['Date'] = email.Utils.formatdate()

        if isinstance(self.event_source_object(), Post):
            msg['Message-ID'] = "<" + self.event_source_object(
            ).message_id + ">"
            if self.event_source_object().parent:
                msg['In-Reply-To'] = "<" + self.event_source_object(
                ).parent.message_id + ">"
        else:
            raise NotImplementedError(
                "TODO:  Implement message id's for non-Post event_source")

        #Archived-At: A direct link to the archived form of an individual email message.
        msg['List-Subscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl(
        )
        msg['List-Unsubscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl(
        )
        msg['Subject'] = Header(self.get_notification_subject(), 'utf-8')

        from_header = Header(self.event_source_object().creator.name, 'utf-8')
        from_header.append(" <" + self.get_from_email_address() + ">", 'ascii')
        msg['From'] = from_header
        msg['To'] = self.get_to_email_address()
        if email_text_part:
            msg.attach(
                SafeMIMEText(email_text_part.encode('utf-8'), 'plain',
                             'utf-8'))
        if email_html_part:
            msg.attach(
                SafeMIMEText(email_html_part.encode('utf-8'), 'html', 'utf-8'))

        return msg.as_string()
Пример #44
0
def mail(message, log_file=0, rtenergo=0):
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    # отправитель
    sender_name = Header("Система загрузки служебных архивов УСПД", "utf-8")
    sender_name.append("<*****@*****.**>", "ascii")
    if rtenergo == 0:
        # получатели
        recipients = ["*****@*****.**", "*****@*****.**"]
    else:
        recipients = "*****@*****.**"
    # тема письма
    subj = "Произведена выгрузка служебных архивов"
    # сообщение
    message = message + '\n'
    # for ms in messages:
    #     message += '\n'+ms.rstrip()
    if rtenergo == 0:
        try:
            with open(log_file, 'r') as logfile:
                for line in logfile.readlines():
                    message += line
        except:
            syslog("Не могу открыть файл-отчет для отправки сообщения!")
            return (1)
    # формирование сообщения
    msg = MIMEText(message, "", "utf-8")
    msg['Subject'] = subj
    msg['From'] = sender_name
    if rtenergo == 0:
        msg['To'] = ', '.join(recipients)
    else:
        msg['To'] = recipients
    # отправка
    server = smtplib.SMTP("192.168.1.1")
    # server.set_debuglevel(1)
    try:
        server.sendmail(sender_name.__str__(), recipients, msg.as_string())
        syslog("Сообщение успешно отправлено по следующим адресам: {0}".format(
            recipients))
    except:
        syslog("Ошибка при отправке сообщения!")
    finally:
        server.quit()
Пример #45
0
    def _from_addr(self, config):
        if config['fromname']:
            from_addr = Header(config['fromname'], 'utf-8')
            try:
                config['fromemail'].encode('ascii')
            except UnicodeEncodeError:
                from_addr.append(f'<{config["fromemail"]}>', 'utf-8')
            else:
                from_addr.append(f'<{config["fromemail"]}>', 'ascii')
        else:
            try:
                config['fromemail'].encode('ascii')
            except UnicodeEncodeError:
                from_addr = Header(config['fromemail'], 'utf-8')
            else:
                from_addr = Header(config['fromemail'], 'ascii')

        return from_addr
Пример #46
0
def compose_email(to_mailbox,
                  from_mailbox,
                  subject,
                  content,
                  to_display_name=None,
                  from_display_name=None,
                  reply_to_mailbox=None,
                  reply_to_display_name=None,
                  sender_mailbox=None,
                  sender_display_name=None,
                  id=None,
                  orig_date=None,
                  **kw):

    # Constructs the email and adds the content
    msg = MIMEText(content, _charset='utf-8')

    # Add mandatory headers
    msg['Message-Id'] = email.utils.make_msgid(
        str(id)) if id else email.utils.make_msgid()
    msg['Date'] = _formatdate(
        orig_date if orig_date else datetime.datetime.now(pytz.utc))
    msg['To'] = _formataddr(to_mailbox, to_display_name, header_name="To")
    msg['From'] = _formataddr(from_mailbox,
                              from_display_name,
                              header_name="From")

    subject_header = Header(header_name="Subject")
    subject_header.append(remove_control_chars(subject))
    msg['Subject'] = subject_header

    # Add "Reply-To" if given
    if reply_to_mailbox:
        msg['Reply-To'] = _formataddr(reply_to_mailbox,
                                      reply_to_display_name,
                                      header_name="Reply-To")

    # Add "Sender" if given
    if sender_mailbox:
        msg['Sender'] = _formataddr(sender_mailbox,
                                    sender_display_name,
                                    header_name="Sender")

    return msg
Пример #47
0
    def test_japanese_codecs(self):
        if due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=360541"):
            return
        eq = self.ndiffAssertEqual
        j = Charset("euc-jp")
        g = Charset("iso-8859-1")
        h = Header("Hello World!")
        jhello = "\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa"
        ghello = "Gr\xfc\xdf Gott!"
        h.append(jhello, j)
        h.append(ghello, g)
        # BAW: This used to -- and maybe should -- fold the two iso-8859-1
        # chunks into a single encoded word.  However it doesn't violate the
        # standard to have them as two encoded chunks and maybe it's
        # reasonable <wink> for each .append() call to result in a separate
        # encoded word.
        eq(
            h.encode(),
            """\
Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=
 =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=""",
        )
        eq(
            decode_header(h.encode()),
            [
                ("Hello World!", None),
                ("\x1b$B%O%m!<%o!<%k%I!*\x1b(B", "iso-2022-jp"),
                ("Gr\xfc\xdf Gott!", "iso-8859-1"),
            ],
        )
        long = "test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9"
        h = Header(long, j, header_name="Subject")
        # test a very long header
        enc = h.encode()
        # TK: splitting point may differ by codec design and/or Header encoding
        eq(
            enc,
            """\
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
 =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""",
        )
        # TK: full decode comparison
        eq(h.__unicode__().encode("euc-jp"), long)
Пример #48
0
def _formataddr(mailbox, display_name=None, header_name=None):
    header = Header(header_name=header_name)
    if display_name:
        display_name_no_control_chars = remove_control_chars(display_name)
        header.append(display_name_no_control_chars)
        if _SPECIALS.search(header.encode()):
            header = Header(header_name=header_name)
            header.append('"%s"' % email.utils.quote(display_name_no_control_chars))
        header.append("<%s>" % encode_domain_as_idna(mailbox))
    else:
        header.append(encode_domain_as_idna(mailbox))
    return header
Пример #49
0
def set_headers(smtp_from, from_email, from_name, to_email, to_name):
    # Antispam don't like when all is in utf-8
    cs = email.charset.Charset('utf-8')
    cs.header_encoding = email.charset.QP
    from_full = Header(from_name, 'ascii')
    from_full.append(f' <{from_email}>', 'ascii')
    to_full = Header(to_name, 'ascii')
    to_full.append(f' <{to_email}>', 'ascii')
    smtp_domain = smtp_from.split('@')[1]
    body_domain = from_email.split('@')[1]

    return {
        'cs': cs,
        'smtp_from': smtp_from,
        'smtp_to': to_email,
        'from_full': from_full,
        'to_full': to_full,
        'smtp_domain': smtp_domain,
        'body_domain': body_domain
    }
Пример #50
0
def _formataddr(mailbox, display_name=None, header_name=None):
    header = Header(header_name=header_name)
    if display_name:
        display_name_no_control_chars = remove_control_chars(display_name)
        header.append(display_name_no_control_chars)
        if _SPECIALS.search(header.encode()):
            header = Header(header_name=header_name)
            header.append('"%s"' %
                          email.utils.quote(display_name_no_control_chars))
        header.append("<%s>" % encode_domain_as_idna(mailbox))
    else:
        header.append(encode_domain_as_idna(mailbox))
    return header
Пример #51
0
 def __init__(self, tweet, to):
     MIMEMultipart.__init__(self, 'alternative', _charset='utf-8')
     
     tweet['html_text'] = Parser().parse(tweet['text']).html
     
     self['Subject'] = Header(tweet['text'].encode('utf-8'), 'utf-8')
     f = Header(tweet['user']['name'].encode('utf-8'), 'utf-8')
     f.append('<{0}@{1}>'.format(tweet['user']['screen_name'], domain), 'ascii')
     self['From'] = f
     self['To'] = to+'@'+domain
     self['Date'] = tweet['created_at']
     self['Message-ID'] = "<{0}@{1}>".format(tweet['id'], domain)
     
     self.attach(MIMEText(tweet['text'].encode('utf-8'), 'plain', _charset='utf-8'))
     
     with codecs.open('mail.html', 'r', 'utf-8') as f:
         template = f.read()
         template = template.format(**tweet)
         template = template.encode('utf-8')
         self.attach(MIMEText(template, 'html', _charset='utf-8'))
Пример #52
0
def send_email(content, name, phone, e_mail):
    """发送邮件"""
    try:
        username = '******'  # 发送人邮箱
        password = '******'  # 发送密钥
        replyto = ''  # 回复邮件接受人邮箱
        receiver = '*****@*****.**'  # 接受者邮箱
        msg = MIMEMultipart('html')
        msg['Subject'] = Header('邮件标题')
        from_header = Header('*****@*****.**', 'utf-8')  # 来自...
        from_header.append('<{}>'.format(username), 'ascii')
        msg['From'] = from_header
        msg['To'] = receiver
        msg['Reply-to'] = replyto
        msg['Message-id'] = email.utils.make_msgid()
        msg['Date'] = email.utils.formatdate()
        content = "邮件内容:" \
                  "<br>" \
                  "<br>" \
                  "<br>" \
                  "{0}" \
                  "<br>" \
                  "<br>" \
                  "<br>" \
                  "来自:{1}" \
                  "<br>" \
                  "联系电话:{2}" \
                  "<br>" \
                  "邮箱地址:{3}".format(content, name, phone, e_mail)
        html = MIMEText(content, _subtype='html', _charset='UTF-8')
        msg.attach(html)
        try:
            client = smtplib.SMTP()
            client.connect('smtpdm.aliyun.com', 80)
            client.login(username, password)
            client.sendmail(username, receiver, msg.as_string())
            client.quit()
        except Exception as e:
            print('1020', e, flush=True)
    except Exception as e:
        print('1022', e, flush=True)
Пример #53
0
def write_patch_file(filename, commit_info, diff):
    """Write patch file"""
    if not diff:
        gbp.log.debug("I won't generate empty diff %s" % filename)
        return None
    try:
        with open(filename, "w") as patch:
            msg = Message()
            charset = Charset("utf-8")
            charset.body_encoding = None
            charset.header_encoding = QP

            # Write headers
            name = commit_info["author"]["name"]
            email = commit_info["author"]["email"]
            # Git compat: put name in quotes if special characters found
            if re.search("[,.@()\[\]\\\:;]", name):
                name = '"%s"' % name
            from_header = Header(unicode(name, "utf-8"), charset, 77, "from")
            from_header.append(unicode("<%s>" % email))
            msg["From"] = from_header
            date = commit_info["author"].datetime
            datestr = date.strftime("%a, %-d %b %Y %H:%M:%S %z")
            msg["Date"] = Header(unicode(datestr, "utf-8"), charset, 77, "date")
            msg["Subject"] = Header(unicode(commit_info["subject"], "utf-8"), charset, 77, "subject")
            # Write message body
            if commit_info["body"]:
                # Strip extra linefeeds
                body = commit_info["body"].rstrip() + "\n"
                try:
                    msg.set_payload(body.encode("ascii"))
                except UnicodeDecodeError:
                    msg.set_payload(body, charset)
            patch.write(msg.as_string(unixfrom=False))

            # Write diff
            patch.write("---\n")
            patch.write(diff)
    except IOError as err:
        raise GbpError("Unable to create patch file: %s" % err)
    return filename
Пример #54
0
    def create_recipients(self, user_list):
        """Creates a unique list of recipients"""

        site = hooks.getSite()
        portal_membership = getToolByName(site, 'portal_membership')

        recipients = Header()

        for user_id in user_list:
            member = portal_membership.getMemberById(user_id)
            if member is None:
                continue
            fullname = member.getProperty('fullname', user_id)
            if not len(fullname):
                fullname = user_id
            email = member.getProperty('email', None)
            if email is None:
                continue
            recipients.append(fullname, 'utf-8')
            recipients.append(' <' + email + '>,')
        return recipients
Пример #55
0
    def mail(self):
        import smtplib
        from email.mime.text import MIMEText
        from email.header import Header

        # отправитель
        sender_name = Header("Система контроля ведения служебных архивов УСПД",
                             "utf-8")
        sender_name.append("<*****@*****.**>", "ascii")

        # получатели
        recipients = ["*****@*****.**", "*****@*****.**"]
        # тема письма
        subj = "Анализ ведения служебных архивов на {0}".format(self.TD)
        # сообщение
        message = ""
        # for ms in messages:
        #     message += '\n'+ms.rstrip()
        try:
            self.LOGFILE.seek(0)
            for i in self.LOGFILE.readlines():
                message += i.encode('utf-8',
                                    'ignore').decode('utf-8', 'ignore')
        except:
            self.syslog("Не могу открыть файл-отчет для отправки сообщения!")
            return (1)
        # формирование сообщения
        msg = MIMEText(message, "", "utf-8")
        msg['Subject'] = subj
        msg['From'] = sender_name
        msg['To'] = ', '.join(recipients)
        # отправка
        server = smtplib.SMTP("192.168.1.1")
        #server.set_debuglevel(1)
        try:
            server.sendmail(sender_name.__str__(), recipients, msg.as_string())
        except:
            self.syslog("Ошибка при отправке сообщения!")
        finally:
            server.quit()
Пример #56
0
    def send_email(self, to_, from_=None, subject=None, body=None,
                   subtype="plain", charset="utf-8"):

        message = MIMEText(body, subtype, charset)

        if subject:
            subject_header = Header()
            subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset)
                       if isinstance(subject, str) else subject)
            subject_header.append(subject.strip())
            message["Subject"] = subject_header

        from_ = from_ or self.default_sender
        from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset)
                 if isinstance(from_, str) else from_)
        from_realname, from_addr = parseaddr(from_)
        from_header = Header()
        from_header.append(formataddr((from_realname, from_addr)))
        message['From'] = from_header

        to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset)
               if isinstance(to_, str) else to_)
        to_realname, to_addr = parseaddr(to_)
        to_header = Header()
        to_header.append(formataddr((to_realname, to_addr)))
        message['To'] = to_header

        self._send(message, from_addr, to_addr)
Пример #57
0
    def send_html_email(self, to_, from_=None, subject=None, text=None,
                        html=None, charset="utf-8"):

        message = MIMEMultipart("alternative")

        if subject:
            subject_header = Header()
            subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset)
                       if isinstance(subject, str) else subject)
            subject_header.append(subject.strip())
            message["Subject"] = subject_header

        from_ = from_ or self.default_sender
        from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset)
                 if isinstance(from_, str) else from_)
        from_realname, from_addr = parseaddr(from_)
        from_header = Header()
        from_header.append(formataddr((from_realname, from_addr)))
        message['From'] = from_header

        to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset)
               if isinstance(to_, str) else to_)
        to_realname, to_addr = parseaddr(to_)
        to_header = Header()
        to_header.append(formataddr((to_realname, to_addr)))
        message['To'] = to_header

        message.attach(MIMEText(text, "plain", charset))
        message.attach(MIMEText(html, "html", charset))

        self._send(message, from_addr, to_addr)
Пример #58
0
def condition_message(to, frm, subject, msg, cc, extra):
    if isinstance(frm, tuple):
	frm = formataddr(frm)
    if isinstance(to, list) or isinstance(to, tuple):
        to = ", ".join([isinstance(addr, tuple) and formataddr(addr) or addr for addr in to if addr])
    if isinstance(cc, list) or isinstance(cc, tuple):
        cc = ", ".join([isinstance(addr, tuple) and formataddr(addr) or addr for addr in cc if addr])
    if frm:
	msg['From'] = frm

    # The following is a hack to avoid an issue with how the email module (as of version 4.0.3)
    # breaks lines when encoding header fields with anything other than the us-ascii codec.
    # This allows the Header implementation to encode each display name as a separate chunk. 
    # The resulting encode produces a string that is us-ascii and has a good density of 
    # "higher-level syntactic breaks"
    to_hdr = Header(header_name='To')
    for name, addr in getaddresses([to]):
        if addr != '' and not addr.startswith('unknown-email-'):
            if name:
                to_hdr.append('"%s"' % name)
            to_hdr.append("<%s>," % addr)
    to_str = to_hdr.encode()
    if to_str and to_str[-1] == ',':
        to_str=to_str[:-1]
    # It's important to use this string, and not assign the Header object.
    # Code downstream from this assumes that the msg['To'] will return a string, not an instance
    msg['To'] = to_str

    if cc:
	msg['Cc'] = cc
    msg['Subject'] = subject
    msg['X-Test-IDTracker'] = (settings.SERVER_MODE == 'production') and 'no' or 'yes'
    msg['X-IETF-IDTracker'] = ietf.__version__
    msg['Auto-Submitted'] = "auto-generated"
    msg['Precedence'] = "bulk"
    if extra:
	for k, v in extra.items():
            if v:
                msg[k] = v
Пример #59
0
def create_and_send_mail_messages(messages, sender_data=None, reply_to=None):
    if not settings.EMAIL_HOST:
        return

    sender = Header(unicode("Google Portal"), 'utf-8')
    
    if sender_data == None:
        sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
        sender = u'%s <%s>' % (unicode("Google Portal"), unicode(settings.DEFAULT_FROM_EMAIL))
    else:
        sender.append('<%s>' % unicode(sender_data['email']))
        sender = u'%s <%s>' % (unicode(sender_data['name']), unicode(sender_data['email']))
        
    
    if reply_to == None:
        reply_to = unicode(settings.DEFAULT_REPLY_TO_EMAIL)
    else:
        reply_to = unicode(reply_to)

    if sender is None:
        sender = str(settings.DEFAULT_FROM_EMAIL)


    for recipient, subject, html, text, media in messages:
        mail_subject = subject

        mail_body  = html

        mail_to = set([
            recipient.email,
        ])
   
        bcc = set()

        mail_from = sender

        attachments = list()

        send_mail(mail_subject, mail_body, mail_from, mail_to, list(bcc), attachments, template_added=True)
Пример #60
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