コード例 #1
0
ファイル: email_util.py プロジェクト: VehpuS/OpenCommunity
def fix_garbled_mail():
    """ 8bit seems to cause buggy emails in Hebrew.  revert back to base64"""
    # In django 1.5, this prevents BASE64:
    from django.core.mail import message
    # let's undo it:
    from email import Charset
    Charset.add_charset('utf-8', Charset.SHORTEST, Charset.BASE64, 'utf-8')
コード例 #2
0
def send_mail(m, subject, target, crici_state):

    # Example address data
    # from_address = [u'⌘Tomek Kopczuk⌘', '*****@*****.**']
    # recipient = [u'Those #!@', '*****@*****.**']

    # Example body
    # text = u'Unicode°\nTest⏎'

    # Default encoding mode set to Quoted Printable. Acts globally!
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "%s" % Header(subject, 'utf-8')
    # Only descriptive part of recipient and sender shall be encoded, not the email address
    # msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1])
    msg['To'] = target

    # Attach both parts
    textpart = MIMEText(m.encode('utf-8'), _charset='utf-8')
    msg.attach(textpart)

    # print str_io.getvalue()
    # print msg.as_string()

    if (critc[0] == 'GK' and crici_state):
        msg['Importance'] = 'High'
    p = subprocess.Popen(['/usr/sbin/sendmail', '-t' ], stdin = subprocess.PIPE)
    p.communicate(msg.as_string())
    return True
コード例 #3
0
ファイル: mailutils.py プロジェクト: nsfw/GlobaLeaks
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body):
    # Override python's weird assumption that utf-8 text should be encoded with
    # base64, and instead use quoted-printable (for both subject and body).  I
    # can't figure out a way to specify QP (quoted-printable) instead of base64 in
    # a way that doesn't modify global state. :-(

    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    # This example is of an email with text and html alternatives.
    multipart = MIMEMultipart('alternative')

    # We need to use Header objects here instead of just assigning the strings in
    # order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so people
    # can read the raw message without getting a headache.
    multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode()
    multipart['Date'] = rfc822_date()

    multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + \
                        " <" + dest_mail + ">"

    multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + \
                        " <" + src_mail + ">"

    multipart['X-Mailer'] = "fnord"

    # Attach the parts with the given encodings.
    # html = '<html>...</html>'
    # htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8')
    # multipart.attach(htmlpart)
    textpart = MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8')
    multipart.attach(textpart)

    return StringIO.StringIO(multipart.as_string())
コード例 #4
0
ファイル: views.py プロジェクト: nisiotis/dideman
def MailSender(name, email):
    mFrom = [u'ΔΔΕ %s' % SETTINGS['dide_place'], SETTINGS['email_dide']]
    mRecipient = [name, email]

    mSubject = u'Ενημέρωση στοιχείων του φακέλου σας.'
    mHtml = u"""<p>Πραγματοποιήθηκε ενημέρωση στοιχείων του φακέλου σας, στο """
    mHtml += u"""σύστημα προσωπικού της ΔΔΕ.</p>"""
    mHtml += u"""<p><a href="http://its.dide.dod.sch.gr">Συνδεθείτε στο """
    mHtml += u"""σύστημα για να δείτε τις αλλαγές</a></p>"""
    mHtml += u"""<p>Απο την ΔΔΕ %s</p>""" % SETTINGS['dide_place']
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "%s" % Header(mSubject, 'utf-8')
    msg['From'] = "\"%s\" <%s>" % (Header(mFrom[0], 'utf-8'), mFrom[1])
    msg['To'] = "\"%s\" <%s>" % (Header(mRecipient[0], 'utf-8'), mRecipient[1])
    htmlpart = MIMEText(mHtml, 'html', 'UTF-8')
    msg.attach(htmlpart)
    str_io = StringIO()
    g = Generator(str_io, False)
    g.flatten(msg)
    s = smtplib.SMTP(settings.EMAIL_HOST, 587)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
    s.sendmail(SETTINGS['email_dide'], email, str_io.getvalue())
コード例 #5
0
ファイル: mailutils.py プロジェクト: br1n0/GlobaLeaks
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body):
    # Override python's weird assumption that utf-8 text should be encoded with
    # base64, and instead use quoted-printable (for both subject and body).  I
    # can't figure out a way to specify QP (quoted-printable) instead of base64 in
    # a way that doesn't modify global state. :-(
    Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8")

    # This example is of an email with text and html alternatives.
    multipart = MIMEMultipart("alternative")

    # We need to use Header objects here instead of just assigning the strings in
    # order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so people
    # can read the raw message without getting a headache.
    multipart["Subject"] = Header(title.encode("utf-8"), "UTF-8").encode()
    multipart["Date"] = rfc822_date()

    multipart["To"] = Header(dest_name.encode("utf-8"), "UTF-8").encode() + " <" + dest_mail + ">"

    multipart["From"] = Header(src_name.encode("utf-8"), "UTF-8").encode() + " <" + src_mail + ">"

    multipart["X-Mailer"] = "fnord"

    textpart = MIMEText(mail_body.encode("utf-8"), "plain", "UTF-8")
    multipart.attach(textpart)

    return StringIO.StringIO(multipart.as_string())
コード例 #6
0
def send_message_notification(sender, instance, **kwargs):
    """
    Send email when user receives a new message. This email contains the full text
    and a link to read it online.

    We trigger this when a MessageRecipient is saved and not when a Message is
    saved because umessages first saves a message and then adds its recipients,
    so when a Message is saved, it doesn't yet have a list of recipients.
    """

    if not instance.user.email:
        # Email can be missing for users registered with Twitter
        # or LinkedIn
        return

    params = {"sender": instance.message.sender.username, "body": instance.message.body}
    message_url_path = reverse("userena_umessages_detail", kwargs={"username": params["sender"]})
    params["message_url"] = "%s://%s%s" % (get_protocol(), Site.objects.get_current(), message_url_path)

    subject = _(u"New message from %(sender)s on Imagination For People") % params
    message = render_to_string("umessages/message_notification.txt", params)
    recipient = instance.user.email

    # XXX Resets the Content-Transfer-Encoding in email header
    # Avoids bad encoding of UTF-8 body
    # See https://code.djangoproject.com/ticket/3472
    from email import Charset

    Charset.add_charset("utf-8", Charset.SHORTEST, "utf-8", "utf-8")

    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [recipient])
コード例 #7
0
ファイル: mail.py プロジェクト: fi-ksi/web-backend
def send(to, subject, text, params={}, bcc=[], cc=[]):
	global emailThread

	Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
	text = u"<html>" + text + u"</html>"

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

	msg['Subject'] = subject
	msg['From'] = config.mail_sender()
	if not 'Sender' in msg: msg['Sender'] = config.get('return_path')
	msg['To'] = (','.join(to)) if isinstance(to, (list)) else to
	if len(cc) > 0: msg['Cc'] = (','.join(cc)) if isinstance(cc, (list)) else cc

	for key in params.keys(): msg[key] = params[key]

	send_to = set((to if isinstance(to, (list)) else [ to ]) +\
	          (cc if isinstance(cc, (list)) else [ cc ]) +\
	          (bcc if isinstance(bcc, (list)) else [ bcc ]))

	# Vlozime email do fronty
	queueLock.acquire()
	emailQueue.put(emailData(msg['Sender'], send_to, msg.as_string()))
	if emailThread and emailThread.isAlive():
		queueLock.release()
	else:
		queueLock.release()
		emailThread = sendThread()
		emailThread.start()
コード例 #8
0
ファイル: email_body.py プロジェクト: StrellaGroup/frappe
	def __init__(self, sender='', recipients=(), subject='', alternative=0, reply_to=None, cc=(), email_account=None, expose_recipients=None):
		from email.mime.multipart import MIMEMultipart
		from email import Charset
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

		if isinstance(recipients, basestring):
			recipients = recipients.replace(';', ',').replace('\n', '')
			recipients = split_emails(recipients)

		# remove null
		recipients = filter(None, (strip(r) for r in recipients))

		self.sender = sender
		self.reply_to = reply_to or sender
		self.recipients = recipients
		self.subject = subject
		self.expose_recipients = expose_recipients

		self.msg_root = MIMEMultipart('mixed')
		self.msg_multipart = MIMEMultipart('alternative')
		self.msg_root.attach(self.msg_multipart)
		self.cc = cc or []
		self.html_set = False

		self.email_account = email_account or get_outgoing_email_account()
コード例 #9
0
ファイル: mail.py プロジェクト: chojar/GlobaLeaks
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body):
    # Override python's weird assumption that utf-8 text should be encoded with
    # base64, and instead use quoted-printable (for both subject and body).  I
    # can't figure out a way to specify QP (quoted-printable) instead of base64 in
    # a way that doesn't modify global state. :-(
    if six.PY2:
        from email import Charset  # pylint: disable=no-name-in-module
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')  # pylint: disable=undefined-variable, no-member

    # This example is of an email with text and html alternatives.
    multipart = MIMEMultipart('alternative')

    # We need to use Header objects here instead of just assigning the strings in
    # order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so people
    # can read the raw message without getting a headache.
    multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode()
    multipart['Date'] = utils.formatdate()
    multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + " <" + dest_mail + ">"
    multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + " <" + src_mail + ">"
    multipart['X-Mailer'] = "fnord"

    multipart.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8'))

    if six.PY2:
        multipart_as_bytes = six.binary_type(multipart.as_string())
    else:
        multipart_as_bytes = multipart.as_bytes()  # pylint: disable=no-member

    return BytesIO(multipart_as_bytes)  # pylint: disable=no-member
コード例 #10
0
ファイル: smtp_helper.py プロジェクト: Rbeuque74/brie-aurore
	def send_email(from_address, recipient, subject, text):
		# Default encoding mode set to Quoted Printable. Acts globally!
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
		 
		# 'alternative’ MIME type – HTML and plain text bundled in one e-mail message
		msg = MIMEMultipart('alternative')
		msg['Subject'] = "%s" % Header(subject, 'utf-8')
		# Only descriptive part of recipient and sender shall be encoded, not the email address
		msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1])
		msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1])
		 
		# Attach both parts
		textpart = MIMEText(text, 'plain', 'UTF-8')
		msg.attach(textpart)
		 
		# Create a generator and flatten message object to 'file’
		str_io = StringIO()
		g = Generator(str_io, False)
		g.flatten(msg)
		# str_io.getvalue() contains ready to sent message
		 
		# Optionally - send it – using python's smtplib
		# or just use Django's

		smtpObj = smtplib.SMTP('smtp.u-psud.fr')
		smtpObj.sendmail(from_address[1], recipient[1], str_io.getvalue())
		#except SMTPException:
        #   print "Error: unable to send email"
        #   raise Exception("Mail non envoyé")

	#end def
#end class
コード例 #11
0
ファイル: app.py プロジェクト: optional-is/What-I-did-today
def send_email(to_email,subject,message):
    # send the message
    smtp = SMTP()
    smtp.connect('smtp.mandrillapp.com', 587)
    smtp.login(os.environ.get('MANDRILL_USERNAME'), os.environ.get('MANDRILL_APIKEY'))
    
    from_addr = "Tindfell <*****@*****.**>"
    to_addr = [to_email]
    
    date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
    
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
    msg = MIMEMultipart("alternative")
    
    msg['From'] = Header(from_addr.encode('utf-8'), 'UTF-8').encode()
    msg['To'] = Header(', '.join(to_addr).encode('utf-8'), 'UTF-8').encode()
    msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()
    
    msg.attach(MIMEText(message.encode('utf-8'),'plain','utf-8'))
    #msg.attach(MIMEText(message.encode('utf-8'),'html','utf-8'))
    
    io = StringIO()
    g = Generator(io, False) # second argument means "should I mangle From?"
    g.flatten(msg)
    
    # For Degubbing
    #print io.getvalue()
    
    # send the message!
    smtp.sendmail(from_addr, to_addr, io.getvalue())
    smtp.quit()
    return
コード例 #12
0
ファイル: mails.py プロジェクト: hdknr/paloma
def create_message(
        addr_from='*****@*****.**',
        addr_to='*****@*****.**',
        message_id=None,
        subject='subject',
        body='body',
        subtype='plain', encoding="utf-8"
):
    ''' Creating Message

    :rtype: SafeMIMTExt(MIMEMixin, email.mime.text.MIMETex)

    - `as_string()` method serializes into string
    '''

    message_id = message_id or uuid.uuid1().hex
    if encoding == "shift_jis":
        #: DoCoMo
        #: TODO chekck message encoding and convert it
        Charset.add_charset(
            'shift_jis', Charset.QP, Charset.BASE64, 'shift_jis')
        Charset.add_codec('shift_jis', 'cp932')

    message = SafeMIMEText(body, subtype, encoding)
    message['Subject'] = subject
    message['From'] = addr_from
    message['To'] = addr_to
    message['Message-ID'] = message_id

    return message
コード例 #13
0
ファイル: pypostman.py プロジェクト: pombredanne/pypostman
    def _assemble_message(self, message):
        subject = SUBJECT
        recipient = RECIPIENT
        from_address = FROMADDR

        text = message.decode('utf-8')
        html = u'<html><body>%s</body></html>' % text

        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

        multipart = MIMEMultipart('alternative')

        multipart['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()
        multipart['To'] = Header(recipient.encode('utf-8'), 'UTF-8').encode()
        multipart['From'] = Header(from_address.encode('utf-8'), 'UTF-8').encode()

        htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8')
        multipart.attach(htmlpart)
        textpart = MIMEText(text.encode('utf-8'), 'plain', 'UTF-8')
        multipart.attach(textpart)

        io = StringIO()
        g = Generator(io, False) # second argument means "should I mangle From?"
        g.flatten(multipart)

        return io.getvalue()
コード例 #14
0
ファイル: uemail.py プロジェクト: selner/pyPocket
    def sendEmail(self, sender=None, recipient_list=None, subject=None, html=None, text=None, files=[]):
        # Default encoding mode set to Quoted Printable. Acts globally!
        Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8")

        if not sender:
            sender = self._sender
        sender_name, sender_addr = parseaddr(sender)

        if isinstance(recipient_list, basestring):
            rlist = recipient_list.split(",")
            if rlist and len(rlist) > 1:
                recipient_list = rlist
            else:
                recipient_list = [recipient_list]

        # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message
        msg = MIMEMultipart()
        msg["From"] = formataddr((sender_name, sender_addr))
        # msg['To'] = formataddr((recipient_name, recipient_addr))
        msg["Subject"] = "%s" % Header(subject, "utf-8")

        # Attach both parts
        if html:
            htmlpart = MIMEText(html, "html", "UTF-8")
            msg.attach(htmlpart)

        if text:
            textpart = MIMEText(u"\n" + text.encode("UTF-8"), "plain", "UTF-8")
            msg.attach(textpart)

        if files:
            for f in files:
                if f:
                    part = MIMEBase("application", "octet-stream")
                    part.set_payload(open(f, "rb").read())
                    encoders.encode_base64(part)
                    part.add_header("Content-Disposition", 'attachment; filename="{0}"'.format(os.path.basename(f)))
                    msg.attach(part)

        try:
            s = smtplib.SMTP(self._smtp_server, self._smtp_port)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(self._user_login, self._user_password)
            ret = s.sendmail(sender, recipient_list, msg.as_string())
            if ret:
                print "Sendmail returned: " + str(ret)

        except Exception, exc:
            print "Error occurred while sending: " + exc.message
            raise
コード例 #15
0
ファイル: mail2web.py プロジェクト: sd2k9/mail2web
def send_mail(command_id, command_raw, payload, rec):
    """Sent the fetched information as Mail to the receiver.

    Parameter
       command_id:  Name of the executed command
       command_raw: Complete command with arguments
       payload: The HTML page to return
       rec: The Mail receiver

    Return: True for OK, False for Failure
    """

    # Override python's weird assumption that utf-8 text should be encoded with base64
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    # First format as a message
    # Create the container (outer) email message.
    msg = MIMEMultipart()
    msg['Subject'] = 'Mail2Web Fetched: ' + command_id
    # me == the sender's email address
    msg['From'] =  Opts['sender']
    msg['To'] = rec
    # Plain text as explanation
    explanation = "This is the demon slave\n" + \
                   "I executed for you:\n" + command_raw + \
                   "\n\nHave fun!\n" + \
                   "To reach some admin, please mailto: admin@thishost\n" + \
                   "This mail address only takes commands for fetching web sites\n" +\
                   "\nPlease be also remindad that this is an beta service. " +\
                   "This means particularly that I am currently logging and " +\
                   "inspecting all accesses."
    # This is they way also Softbank Phones understand it
    msg_explanation = MIMEText(explanation, "plain", "utf-8" ) # And the explanation as text
    msg_explanation.add_header('Content-Disposition', 'inline')  # Show message inline
    msg.attach(msg_explanation)
    # And our HTML we want to send, and it's an attachment
    msg_payload = MIMEText(payload, "html", "utf-8")
    msg_payload.add_header('Content-Disposition', 'attachment; filename="result.html"')
    msg.attach(msg_payload)

    # Send the email via our own SMTP server.
    # Debug
    # print msg.as_string()
    # return False
    pinfo("Will send the result now to " + rec + " ...")
    try:   # Open Connection; Catch exceptions
        smtp = smtplib.SMTP(Opts['smtp_server_host'], Opts['smtp_server_port'])
    except (smtplib.SMTPException, socket.error), detail:
        perror("Establishing SMTP connection to " + \
                   Opts['smtp_server_host'] + ":"  + Opts['smtp_server_port'] + \
                   " failed: " + str(detail))
        return False
コード例 #16
0
ファイル: utils.py プロジェクト: TAKSIM/camp
def sendmail(sender, to, subject, contents, texttype='plain'):
    Charset.add_charset(encode, Charset.QP, Charset.QP, encode)
    msg = MIMEText(contents, texttype, encode)
    msg['Subject'] = Header(subject.encode(encode), encode).encode()
    msg['From'] = sender
    msg['To'] = ', '.join(to)
    s = SMTP('smtp.exmail.qq.com')
    s.ehlo('smtp.exmail.qq.com')
    s.set_debuglevel(False)
    s.login('*****@*****.**','GMvsBWKwZty47LG2') # access code is generated from web (settings->account->wechat code)
    try:
        s.sendmail(sender, to, msg.as_string())
    finally:
        s.quit()
コード例 #17
0
ファイル: mail.py プロジェクト: chrneumann/cu
def send_emails(customers, template, host, port, user, password):
    """Send emails to customers.
    """
    mails = []
    for customer in customers:
        yaml = render_template(template, customer)
        data = load(yaml, Loader=Loader)
        # Use quoted printable instead of base64
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
        mail = MIMEText(data['body'], _charset='utf-8')
        mail['From'] = data['from']
        mail['To'] = data['to']
        mail['Subject'] = data['subject']
        mails.append(mail)
    transfer_emails(mails, host, port, user, password)
コード例 #18
0
ファイル: utils.py プロジェクト: TAKSIM/fwm
def sendmail(sender, to, subject, contents, texttype='html'):
    Charset.add_charset(encode, Charset.QP, Charset.QP, encode)
    msg = MIMEText(contents, texttype, encode)
    msg['Subject'] = Header(subject.encode(encode), encode).encode()
    msg['From'] = sender
    msg['To'] = ', '.join(to)
    s = SMTP('smtp.exmail.qq.com')
    s.set_debuglevel(False)
    s.ehlo('smtp.exmail.qq.com')
    s.login('*****@*****.**', '1qaz@WSX')
    import pandas
    pandas.read_ex
    try:
        s.sendmail(sender, to, msg.as_string())
    finally:
        s.quit()
コード例 #19
0
ファイル: command.py プロジェクト: jhcepas/alot
    def apply(self, ui):
        if not self.message:
            self.message = ui.current_buffer.get_selected_message()
        mail = self.message.get_email()

        reply = MIMEMultipart()
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
        if self.inline:  # inline mode
            # set body text
            author = self.message.get_author()[0]
            mailcontent = '\nForwarded message from %s:\n' % author
            for line in self.message.accumulate_body().splitlines():
                mailcontent += '>' + line + '\n'

            bodypart = MIMEText(mailcontent.encode('utf-8'), 'plain', 'UTF-8')
            reply.attach(bodypart)

        else:  # attach original mode
            # create empty text msg
            bodypart = MIMEText('', 'plain', 'UTF-8')
            reply.attach(bodypart)
            # attach original msg
            reply.attach(mail)

        # copy subject
        subject = mail.get('Subject', '')
        subject = 'Fwd: ' + subject
        reply['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()

        # set From
        my_addresses = ui.accountman.get_addresses()
        matched_address = ''
        in_to = [a for a in my_addresses if a in mail.get('To', '')]
        if in_to:
            matched_address = in_to[0]
        else:
            cc = mail.get('Cc', '') + mail.get('Bcc', '')
            in_cc = [a for a in my_addresses if a in cc]
            if in_cc:
                matched_address = in_cc[0]
        if matched_address:
            account = ui.accountman.get_account_by_address(matched_address)
            fromstring = '%s <%s>' % (account.realname, account.address)
            reply['From'] = encode_header('From', fromstring)
        ui.apply_command(ComposeCommand(mail=reply))
コード例 #20
0
ファイル: __init__.py プロジェクト: pythontech/ptforum
 def forum_post_as_email(self, forum, post):
     '''Convert a post to email'''
     topic = post.topic
     sre, subject = re.match(r'(Re: )?(.*)',
                             post.subject).groups()
     if subject == '':
         if post.pid != topic.firstpost:
             sre = 'Re: '
         subject = topic.title or 'topic %s' % topic.tid
     subject = (sre or '') + forum.subjectPrefix + subject
     if post.datetime is not None:
         pass
     zauthor,n = re.subn(r'[^-A-Za-z0-9]+','_', post.author)
     fromm = _subst(self.fromPattern, u=zauthor)
     msgid = _subst(self.messageIdPattern, p=post.pid)
     hbody = '<html><body>%s</body></html>' % post.body.encode('utf-8')
     try:
         from email.Message import Message 
         from email.Header import Header
         from email.Utils import formatdate
         # Force quoted-printable for utf-8 instead of base64 (for Thunderbird "View source")
         import email.Charset as cs
         cs.add_charset('utf-8', cs.SHORTEST, cs.QP, 'utf-8')
     except ImportError:
         from email.message import Message
         from email.header import Header
         from email.utils import formatdate
     msg = Message()
     msg.add_header('From', fromm)
     msg.add_header('To', forum.recipient)
     hsubj = Header(subject)
     msg.add_header('Subject', str(hsubj))
     msg.add_header('Message-ID', '<%s>' % msgid)
     if topic.firstpost:
         firstid = _subst(self.messageIdPattern, p=topic.firstpost)
         msg.add_header('In-Reply-To', '<%s>' % firstid)
         msg.add_header('References', '<%s>' % firstid)
     if post.datetime is not None:
         date = formatdate(post.datetime)
         msg.add_header('Date', date)
     msg.set_payload(hbody)
     msg.set_type('text/html')
     msg.set_charset('utf-8')
     return msg.as_string()
コード例 #21
0
def MIME_mail_build(source_name, source_mail, receiver_name, receiver_mail, title, txt_body):

    # Override python's weird assumption that utf-8 text should be encoded with
    # base64, and instead use quoted-printable (for both subject and body).  I
    # can't figure out a way to specify QP (quoted-printable) instead of base64 in
    # a way that doesn't modify global state. :-(

    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    # This example is of an email with text and html alternatives.
    multipart = MIMEMultipart('alternative')

    # We need to use Header objects here instead of just assigning the strings in
    # order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so people
    # can read the raw message without getting a headache.
    multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode()
    multipart['Date'] = rfc822_date()

    multipart['To'] = Header(receiver_name.encode('utf-8'), 'UTF-8').encode() + \
                        " <" + receiver_mail + ">"

    multipart['From'] = Header(source_name.encode('utf-8'), 'UTF-8').encode() + \
                        " <" + source_mail + ">"

    multipart['X-Mailer'] = "fnord"

    # Attach the parts with the given encodings.
    # html = '<html>...</html>'
    # htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8')
    # multipart.attach(htmlpart)

    textpart = MIMEText(txt_body.encode('utf-8'), 'plain', 'UTF-8')
    multipart.attach(textpart)

    # And here we have to instantiate a Generator object to convert the multipart
    # object to a string (can't use multipart.as_string, because that escapes
    # "From" lines).
    try:
        io = StringIO.StringIO(multipart.as_string())
        return io
    except Exception as excep:
        log.err("Unable to encode and email: %s" % excep)
        return None
コード例 #22
0
ファイル: send.py プロジェクト: beliezer/wnframework
	def __init__(self, sender='', recipients=[], subject='', from_defs=0, alternative=0, reply_to=None):
		from email.mime.multipart import MIMEMultipart
		from email import Charset
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

		if isinstance(recipients, basestring):
			recipients = recipients.replace(';', ',')
			recipients = recipients.split(',')
			
		self.from_defs = from_defs
		self.sender = sender
		self.reply_to = reply_to or sender
		self.recipients = recipients
		self.subject = subject
		
		self.msg_root = MIMEMultipart('mixed')
		self.msg_multipart = MIMEMultipart('alternative')
		self.msg_root.attach(self.msg_multipart)
		self.cc = []
コード例 #23
0
ファイル: sendtest.py プロジェクト: baydinsoftware/remindme
	def handle_noargs(self, **options):
		subject = 'hi krista'
		fromName = 'krista'
		fromAddress = '*****@*****.**'
		toAddressesStr = '*****@*****.**'
		textBody = 'hihihi'
		htmlBody = 'body yo yo yo'
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
    		msg = MIMEMultipart('alternative')
    		msg['Subject'] = subject
    		msg['From'] = "" + str(fromName) + " <" + fromAddress + ">"
    		msg['To'] = toAddressesStr
    
    		connection = SESConnection(aws_access_key_id=settings.AWS_ACCESS_KEY, 
				aws_secret_access_key=settings.AWS_SECRET_KEY)
    		connection.send_email(fromName + " <" + fromAddress + ">", 
			subject, body=htmlBody, 
			to_addresses=toAddressesStr, text_body=textBody, 
			format="html", return_path=fromAddress)
コード例 #24
0
ファイル: hooklib.py プロジェクト: ollyja/repo-management
    def __init__(self, ref, old_sha1, new_sha1, push_user):
        "Create a Repository object"

        # Save configuration
        self.ref = ref
        self.old_sha1 = old_sha1
        self.new_sha1 = new_sha1
        self.push_user = push_user
        self.commits = OrderedDict()

        # Find our configuration directory....
        if os.getenv('REPO_MGMT'):
            self.management_directory = os.getenv('REPO_MGMT')
        else:
            self.management_directory = os.getenv('HOME') + "/" + Repository.RepoManagementName

        # Set path and id....
        path_match = re.match("^"+Repository.BaseDir+"(.+).git$", os.getcwd())
        self.path = path_match.group(1)
        self.uid = self.__get_repo_id()
        self.__write_metadata()

        # Determine types....
        self.repo_type = self.__get_repo_type()
        self.ref_type = self.__get_ref_type()
        self.change_type = self.__get_change_type()
        ref_name_match = re.match("^refs/(.+?)/(.+)$", self.ref)
        self.ref_name = ref_name_match.group(2)

        # Determine commit type for the top most commit
        if self.change_type == ChangeType.Delete:
            self.commit_type = "commit"
        else:
            command = ["git", "cat-file", "-t", self.new_sha1]
            process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            self.commit_type = process.stdout.readline().strip()

        # Final initialisation
        self.__build_commits()

        # Ensure emails get done using the charset encoding method we want, not what Python thinks is best....
        Charset.add_charset("utf-8", Charset.QP, Charset.QP)
コード例 #25
0
ファイル: mailer.py プロジェクト: malbammae/ZmastChile
    def enviar(self,destino,asunto,mensaje):
        smtpserver = smtplib.SMTP(self.smtp,self.puerto)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(self.user, self.passwd)
        """header = 'To:' + destino + '\n' + 'From: ' + self.user + '\n' + 'Subject:'+asunto+' \n'
        msg = header + '\n'+mensaje+'\n\n'"""
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
        msg = MIMEMultipart('alternative')
        msg['To'] = destino
        msg['From'] = self.user
        msg['Subject'] = asunto
        part2 = MIMEText(mensaje.encode('utf-8'), 'html')
        msg.attach(part2)
 

        smtpserver.sendmail(self.user, destino, msg.as_string())
        smtpserver.quit()
        """
コード例 #26
0
ファイル: send.py プロジェクト: Vichagserp/cimworks
    def __init__(self, sender="", recipients=[], subject="", from_defs=0, alternative=0, reply_to=None):
        from email.mime.multipart import MIMEMultipart
        from email import Charset

        Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8")

        if type(recipients) == str:
            recipients = recipients.replace(";", ",")
            recipients = recipients.split(",")

        self.from_defs = from_defs
        self.sender = sender
        self.reply_to = reply_to or sender
        self.recipients = recipients
        self.subject = subject

        self.msg_root = MIMEMultipart("mixed")
        self.msg_multipart = MIMEMultipart("alternative")
        self.msg_root.attach(self.msg_multipart)
        self.cc = []
コード例 #27
0
ファイル: smtp.py プロジェクト: appost/wnframework
	def __init__(self, sender='', recipients=[], subject='', alternative=0, reply_to=None):
		from email.mime.multipart import MIMEMultipart
		from email import Charset
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

		if isinstance(recipients, basestring):
			recipients = recipients.replace(';', ',').replace('\n', '')
			recipients = recipients.split(',')
		
		# remove null
		recipients = filter(None, (r.strip() for r in recipients))
		
		self.sender = sender
		self.reply_to = reply_to or sender
		self.recipients = recipients
		self.subject = subject
		
		self.msg_root = MIMEMultipart('mixed')
		self.msg_multipart = MIMEMultipart('alternative')
		self.msg_root.attach(self.msg_multipart)
		self.cc = []
		self.html_set = False
コード例 #28
0
ファイル: common.py プロジェクト: ingridjl/userscripts
def send_mail(sender, recipient, subject, body):
    # Default encoding mode set to Quoted Printable. Acts globally!
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    msg = MIMEMultipart()
    msg['Subject'] = "%s" % Header(subject, 'utf-8')
    # Only descriptive part of recipient and sender shall be encoded,
    # not the email address
    msg['From'] = "\"%s\" <%s>" % (Header(sender[0], 'utf-8'), sender[1])
    msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1])

    msg.attach(MIMEText(body, 'plain', 'UTF-8'))

    str_io = StringIO()
    g = Generator(str_io, False)
    g.flatten(msg)

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail('', recipient[1], str_io.getvalue())
    except smtplib.SMTPException, e:
        print e
コード例 #29
0
def make_me_msg(me, you, subject, preamble, postamble, text_size, attachments):
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = me
    msg['To'] = you
        
    text = preamble + "\n\n" + give_me_text(text_size, "", "\n\n") + postamble
    html = "<html><head></head><body><p>%s</p></body></html>" % text.replace("\n\n", "</p><p>")
    msg.attach(MIMEText(text, 'plain','utf-8'))
    msg.attach(MIMEText(html, 'html', 'utf-8'))
        
    for attachment in attachments:
        filepath, type, params = attachment
        fp = open(filepath, 'rb')
        if type == "image":
            i = MIMEImage(fp.read());
            for key,value in params.items():
                i.add_header(key,value)
            msg.attach(i)
        fp.close()
    
    return msg
コード例 #30
0
ファイル: email_body.py プロジェクト: vrms/frappe
    def __init__(self, sender="", recipients=(), subject="", alternative=0, reply_to=None, cc=()):
        from email.mime.multipart import MIMEMultipart
        from email import Charset

        Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8")

        if isinstance(recipients, basestring):
            recipients = recipients.replace(";", ",").replace("\n", "")
            recipients = split_emails(recipients)

            # remove null
        recipients = filter(None, (strip(r) for r in recipients))

        self.sender = sender
        self.reply_to = reply_to or sender
        self.recipients = recipients
        self.subject = subject

        self.msg_root = MIMEMultipart("mixed")
        self.msg_multipart = MIMEMultipart("alternative")
        self.msg_root.attach(self.msg_multipart)
        self.cc = cc or []
        self.html_set = False
コード例 #31
0
ファイル: client.py プロジェクト: sm6xmm/ep-tools
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.generator import Generator

try:
    from email import Charset as charset
    from cStringIO import StringIO
except:
    from io import StringIO
    from email import charset

# Default encoding mode set to Quoted Printable. Acts globally!
charset.add_charset('utf-8', charset.QP, charset.QP, 'utf-8')

# from   credentials          import GMAIL_MAILADDR, GMAIL_PASSWORD, GMAIL_SENDER_NAME
# GMAIL_SENDER = (GMAIL_SENDER_NAME, GMAIL_MAILADDR)
#
# from   credentials          import PYSS_MAILADDR, PYSS_PASSWORD, PYSS_SENDER_NAME
# PYSS_SENDER = (PYSS_SENDER_NAME, PYSS_MAILADDR)


class EMailClient(object):

    _smtpserver = ''
    _serverport = ''

    def __init__(self, username, password, smtpserver='', serverport=''):
        self.username = username
コード例 #32
0
ファイル: mail.py プロジェクト: twocngdagz/weppy
    def send(
        self,
        to,
        subject = '[no subject]',
        message = '[no message]',
        attachments=None,
        cc=None,
        bcc=None,
        reply_to=None,
        sender=None,
        encoding='utf-8',
        raw=False,
        headers={}
    ):
        """
        Sends an email using data specified in constructor

        Arguments:

            to: list or tuple of receiver addresses; will also accept single
                object
            subject: subject of the email
            message: email body text; depends on type of passed object:
                     if 2-list or 2-tuple is passed: first element will be
                     source of plain text while second of html text;
                     otherwise: object will be the only source of plain text
                     and html source will be set to None;
                     If text or html source is:
                     None: content part will be ignored,
                     string: content part will be set to it,
                     file-like object: content part will be fetched from
                                       it using it's read() method
            attachments: list or tuple of Mail.Attachment objects; will also
                         accept single object
            cc: list or tuple of carbon copy receiver addresses; will also
                accept single object
            bcc: list or tuple of blind carbon copy receiver addresses; will
                also accept single object
            reply_to: address to which reply should be composed
            encoding: encoding of all strings passed to this method (including
                      message bodies)
            headers: dictionary of headers to refine the headers just before
                     sending mail, e.g. {'Return-Path' : '*****@*****.**'}

        Examples:

            #Send plain text message to single address:
            mail.send('*****@*****.**',
                      'Message subject',
                      'Plain text body of the message')

            #Send html message to single address:
            mail.send('*****@*****.**',
                      'Message subject',
                      '<html>Plain text body of the message</html>')

            #Send text and html message to three addresses (two in cc):
            mail.send('*****@*****.**',
                      'Message subject',
                      ('Plain text body', '<html>html body</html>'),
                      cc=['*****@*****.**', '*****@*****.**'])

            #Send html only message with image attachment available from
            the message by 'photo' content id:
            mail.send('*****@*****.**',
                      'Message subject',
                      (None, '<html><img src="cid:photo" /></html>'),
                      Mail.Attachment('/path/to/photo.jpg'
                                      content_id='photo'))

            #Send email with two attachments and no body text
            mail.send('[email protected],
                      'Message subject',
                      None,
                      [Mail.Attachment('/path/to/fist.file'),
                       Mail.Attachment('/path/to/second.file')])

        Returns True on success, False on failure.

        Before return, method updates two object's fields:
        self.result: return value of smtplib.SMTP.sendmail() or GAE's
                     mail.send_mail() method
        self.error: Exception message or None if above was successful
        """

        # We don't want to use base64 encoding for unicode mail
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

        def encode_header(key):
            if [c for c in key if 32 > ord(c) or ord(c) > 127]:
                return Header.Header(key.encode('utf-8'), 'utf-8')
            else:
                return key

        # encoded or raw text
        def encoded_or_raw(text):
            if raw:
                text = encode_header(text)
            return text

        sender = sender or self.settings.sender

        if not isinstance(self.settings.server, str):
            raise Exception('Server address not specified')
        if not isinstance(sender, str):
            raise Exception('Sender address not specified')

        if not raw and attachments:
            # Use multipart/mixed if there is attachments
            payload_in = MIMEMultipart.MIMEMultipart('mixed')
        elif raw:
            # no encoding configuration for raw messages
            if not isinstance(message, basestring):
                message = message.read()
            if isinstance(message, unicode):
                text = message.encode('utf-8')
            elif not encoding == 'utf-8':
                text = message.decode(encoding).encode('utf-8')
            else:
                text = message
            # No charset passed to avoid transport encoding
            # NOTE: some unicode encoded strings will produce
            # unreadable mail contents.
            payload_in = MIMEText.MIMEText(text)
        if to:
            if not isinstance(to, (list, tuple)):
                to = [to]
        else:
            raise Exception('Target receiver address not specified')
        if cc:
            if not isinstance(cc, (list, tuple)):
                cc = [cc]
        if bcc:
            if not isinstance(bcc, (list, tuple)):
                bcc = [bcc]
        if message is None:
            text = html = None
        elif isinstance(message, (list, tuple)):
            text, html = message
        elif message.strip().startswith('<html') and \
                message.strip().endswith('</html>'):
            text = self.settings.server == 'gae' and message or None
            html = message
        else:
            text = message
            html = None

        if (not text is None or not html is None) and (not raw):

            if not text is None:
                if not isinstance(text, basestring):
                    text = text.read()
                if isinstance(text, unicode):
                    text = text.encode('utf-8')
                elif not encoding == 'utf-8':
                    text = text.decode(encoding).encode('utf-8')
            if not html is None:
                if not isinstance(html, basestring):
                    html = html.read()
                if isinstance(html, unicode):
                    html = html.encode('utf-8')
                elif not encoding == 'utf-8':
                    html = html.decode(encoding).encode('utf-8')

            # Construct mime part only if needed
            if text is not None and html:
                # We have text and html we need multipart/alternative
                attachment = MIMEMultipart.MIMEMultipart('alternative')
                attachment.attach(MIMEText.MIMEText(text, _charset='utf-8'))
                attachment.attach(
                    MIMEText.MIMEText(html, 'html', _charset='utf-8'))
            elif text is not None:
                attachment = MIMEText.MIMEText(text, _charset='utf-8')
            elif html:
                attachment = \
                    MIMEText.MIMEText(html, 'html', _charset='utf-8')

            if attachments:
                # If there is attachments put text and html into
                # multipart/mixed
                payload_in.attach(attachment)
            else:
                # No attachments no multipart/mixed
                payload_in = attachment

        if (attachments is None) or raw:
            pass
        elif isinstance(attachments, (list, tuple)):
            for attachment in attachments:
                payload_in.attach(attachment)
        else:
            payload_in.attach(attachments)

        #######################################################
        #                      CIPHER                         #
        #######################################################
        cipher_type = self.settings.cipher_type
        sign = self.settings.sign
        sign_passphrase = self.settings.sign_passphrase
        encrypt = self.settings.encrypt
        #######################################################
        #                       GPGME                         #
        #######################################################
        if cipher_type == 'gpg':
            if self.settings.gpg_home:
                # Set GNUPGHOME environment variable to set home of gnupg
                import os
                os.environ['GNUPGHOME'] = self.settings.gpg_home
            if not sign and not encrypt:
                self.error = "No sign and no encrypt is set but cipher type to gpg"
                return False

            # need a python-pyme package and gpgme lib
            from pyme import core, errors
            from pyme.constants.sig import mode
            ############################################
            #                   sign                   #
            ############################################
            if sign:
                import string
                core.check_version(None)
                pin = string.replace(payload_in.as_string(), '\n', '\r\n')
                plain = core.Data(pin)
                sig = core.Data()
                c = core.Context()
                c.set_armor(1)
                c.signers_clear()
                # search for signing key for From:
                for sigkey in c.op_keylist_all(sender, 1):
                    if sigkey.can_sign:
                        c.signers_add(sigkey)
                if not c.signers_enum(0):
                    self.error = 'No key for signing [%s]' % sender
                    return False
                c.set_passphrase_cb(lambda x, y, z: sign_passphrase)
                try:
                    # make a signature
                    c.op_sign(plain, sig, mode.DETACH)
                    sig.seek(0, 0)
                    # make it part of the email
                    payload = MIMEMultipart.MIMEMultipart('signed',
                                                          boundary=None,
                                                          _subparts=None,
                                                          **dict(
                                                          micalg="pgp-sha1",
                                                          protocol="application/pgp-signature"))
                    # insert the origin payload
                    payload.attach(payload_in)
                    # insert the detached signature
                    p = MIMEBase.MIMEBase("application", 'pgp-signature')
                    p.set_payload(sig.read())
                    payload.attach(p)
                    # it's just a trick to handle the no encryption case
                    payload_in = payload
                except errors.GPGMEError, ex:
                    self.error = "GPG error: %s" % ex.getstring()
                    return False
            ############################################
            #                  encrypt                 #
            ############################################
            if encrypt:
                core.check_version(None)
                plain = core.Data(payload_in.as_string())
                cipher = core.Data()
                c = core.Context()
                c.set_armor(1)
                # collect the public keys for encryption
                recipients = []
                rec = to[:]
                if cc:
                    rec.extend(cc)
                if bcc:
                    rec.extend(bcc)
                for addr in rec:
                    c.op_keylist_start(addr, 0)
                    r = c.op_keylist_next()
                    if r is None:
                        self.error = 'No key for [%s]' % addr
                        return False
                    recipients.append(r)
                try:
                    # make the encryption
                    c.op_encrypt(recipients, 1, plain, cipher)
                    cipher.seek(0, 0)
                    # make it a part of the email
                    payload = MIMEMultipart.MIMEMultipart('encrypted',
                                                          boundary=None,
                                                          _subparts=None,
                                                          **dict(protocol="application/pgp-encrypted"))
                    p = MIMEBase.MIMEBase("application", 'pgp-encrypted')
                    p.set_payload("Version: 1\r\n")
                    payload.attach(p)
                    p = MIMEBase.MIMEBase("application", 'octet-stream')
                    p.set_payload(cipher.read())
                    payload.attach(p)
                except errors.GPGMEError, ex:
                    self.error = "GPG error: %s" % ex.getstring()
                    return False
コード例 #33
0
try:
    from email.MIMEText import MIMEText
except:
    from email.mime.text import MIMEText
from email.header import Header
from email.generator import Generator
try:
    from email import Charset
except:
    from email import charset as Charset
try:
    from email import Encoders
except:
    from email import encoders as Encoders

Charset.add_charset('utf-8', Charset.BASE64, Charset.BASE64, 'utf-8')

# default the email messages to plain text
# unless otherwise specified
message_flag = "plain"

# import the core modules
from src.core.setcore import *

# do we want to track the users that click links
track_email = check_config("TRACK_EMAIL_ADDRESSES=").lower()

definepath = os.getcwd()

# DEFINE SENDMAIL CONFIG and WEB ATTACK
sendmail = 0
コード例 #34
0
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.generator import Generator

try:
    # noinspection PyStatementEffect
    from email import Charset as charset
    from cStringIO import StringIO
except ImportError:
    from io import StringIO
    from email import charset

# Default encoding mode set to Quoted Printable. Acts globally!
charset.add_charset("utf-8", charset.QP, charset.QP, "utf-8")

# from   credentials          import GMAIL_MAILADDR, GMAIL_PASSWORD, GMAIL_SENDER_NAME
# GMAIL_SENDER = (GMAIL_SENDER_NAME, GMAIL_MAILADDR)
#
# from   credentials          import PYSS_MAILADDR, PYSS_PASSWORD, PYSS_SENDER_NAME
# PYSS_SENDER = (PYSS_SENDER_NAME, PYSS_MAILADDR)


class EMailClient(object):

    _smtpserver = ""
    _serverport = ""

    def __init__(self, username, password, smtpserver="", serverport=""):
        self.username = username
コード例 #35
0
ファイル: utils.py プロジェクト: yasusii/shaling
#!/usr/bin/env python
import sys, os, re, time
import config
from email import Utils, Header, Charset
stderr = sys.stderr

# ms932 hack
Charset.add_codec('shift_jis', 'ms932')

##  String utilities
##

# get_msgids
MSGID_PAT = re.compile(r'<[^>]+>')


def get_msgids(x):
    return [m.group(0) for m in MSGID_PAT.finditer(x or '')]


# get_numbers
NUM_PAT = re.compile(r'\d+')


def get_numbers(x):
    return [int(m.group(0)) for m in NUM_PAT.finditer(x)]


# rmsp
RMSP_PAT = re.compile(r'\s+', re.UNICODE)
コード例 #36
0
def create_raw_email(recipients,
                     from_address,
                     subject,
                     body,
                     attachments=None,
                     extra_headers=None):
    '''
    Creates a i18n-compatible raw email.
    recipients may be an array of address or a single address string.
    body may be an array of MIME parts in the form:
        [['plain', plainbody], ['html', htmlbody], ...]
    May raise exceptions, such as if character encodings fail.
    attachment should be an array of tuples of (file-type-object, display-filename).
    extra_headers should be a dictionary of header-name:header-string values.
    '''

    # For email with attachments, the MIME structure will be as follows:
    #    multipart/mixed
    #        multipart/alternative
    #            text/plain - the plain text message
    #            text/html - the html message
    #        application/octet-stream - the first attachment
    #        application/octet-stream - the second attachment, etc.
    #
    # For email without an attachment, it will be the same, but we'll omit the
    # last piece.

    # We expect body to be an array of mime parts. So make one if that's not
    # what we got.
    if isinstance(body, str) or isinstance(body, unicode):
        body = [
            ['plain', body],
        ]
    if body is None:
        body = []

    # Override python's weird assumption that utf-8 text should be encoded with
    # base64, and instead use quoted-printable (for both subject and body).  I
    # can't figure out a way to specify QP (quoted-printable) instead of base64 in
    # a way that doesn't modify global state. :-(
    Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

    # The root MIME section.
    msgRoot = MIMEMultipart('mixed')

    # We need to use Header objects here instead of just assigning the strings in
    # order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so people
    # can read the raw message without getting a headache.

    # NOTE: encoding the email addresses in UTF-8 did not work with AmazonSES,
    # and it's not clear if it's necessary to do so. Some day we should determine
    # a) if there's a reason to UTF-8 encode, and b) if it's okay to UTF-8 encode
    # now that we're sending directly with SMTP.
    #multipart['To'] = Header(recipient.encode('utf-8'), 'UTF-8').encode()
    #multipart['From'] = Header(from_address.encode('utf-8'), 'UTF-8').encode()

    if type(recipients) == list:
        recipients = ', '.join(recipients)

    msgRoot['To'] = Header(recipients.encode('utf-8'), 'ascii').encode()
    msgRoot['From'] = Header(from_address.encode('utf-8'), 'ascii').encode()

    msgRoot['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()

    if extra_headers:
        for header_name, header_value in extra_headers.iteritems():
            # We need a special case for the Reply-To header. Like To and From,
            # it needs to be ASCII encoded.
            encoding = 'UTF-8'
            if header_name.lower() == 'reply-to':
                encoding = 'ascii'
            msgRoot[header_name] = Header(header_value.encode('utf-8'),
                                          encoding).encode()

    # The MIME section that contains the plaintext and HTML alternatives.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    # Attach the body alternatives with the given encodings.
    for mimetype, content in body:
        msgpart = MIMEText(content.encode('utf-8'), mimetype, 'UTF-8')
        msgAlternative.attach(msgpart)

    # Attach the attachments
    if attachments:
        for attachment in attachments:
            fp, filename = attachment

            msgAttachment = MIMEBase('application', 'octet-stream')

            msgAttachment.add_header('Content-Disposition',
                                     'attachment',
                                     filename=filename)

            msgAttachment.set_payload(fp.read())
            fp.close()

            encoders.encode_base64(msgAttachment)

            msgRoot.attach(msgAttachment)

    # And here we have to instantiate a Generator object to convert the multipart
    # object to a string (can't use multipart.as_string, because that escapes
    # "From" lines).

    io = StringIO()
    g = Generator(io, False)  # second argument means "should I mangle From?"
    g.flatten(msgRoot)

    return io.getvalue()
コード例 #37
0
ファイル: mime.py プロジェクト: lvh/txeasymail
from email import Charset, generator, header
from email.mime import multipart, text
from email.utils import formataddr, parseaddr

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

# Yay global state!
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')


def buildMessage(headers, parts):
    """
    Builds a message from some headers and MIME parts.
    """
    message = multipart.MIMEMultipart('alternative')

    for name, value in headers.iteritems():
        name = name.title()
        if name == "From":
            multipart[name] = _encodeAddress(value)
        elif name in ["To", "Cc", "Bcc"]:
            multipart[name] = _encodeAddresses(value)
        else:
            multipart[name] = _encodeHeader(value)

    for partType, part in parts.iteritems():
        mimeText = text.MIMEText(part.encode("utf-8"), partType, "UTF-8")
        message.attach(mimeText.encode())
コード例 #38
0
import time
from email import Charset, Encoders
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.Header import Header
from email.Utils import formatdate, getaddresses, formataddr

from django.conf import settings
from django.core.mail.utils import DNS_NAME
from django.utils.encoding import smart_str, force_unicode
from email.Utils import parseaddr

# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from
# some spam filters.
Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8')

# Default MIME type to use on attachments (if it is not explicitly given
# and cannot be guessed).
DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream'


class BadHeaderError(ValueError):
    pass


# Copied from Python standard library, with the following modifications:
# * Used cached hostname for performance.
# * Added try/except to support lack of getpid() in Jython (#5496).
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
コード例 #39
0
def send_email(dbo,
               fromadd,
               toadd,
               ccadd="",
               subject="",
               body="",
               contenttype="plain"):
    """
    Sends an email.
    fromadd is an RFC821 address
    toadd is a comma separated list of RFC821 addresses
    ccadd is a comma separated list of RFC821 addresses
    subject, body are strings
    contenttype is either "plain" or "html"
    """
    def parse_email(s):
        # Returns a tuple of description and address
        s = s.strip()
        fp = s.find("<")
        ep = s.find(">")
        description = s
        address = s
        if fp != -1 and ep != -1:
            description = s[0:fp].strip()
            address = s[fp + 1:ep].strip()
        return (description, address)

    def strip_email(s):
        # Just returns the address portion of an email
        description, address = parse_email(s)
        return address

    def add_header(msg, header, value):
        # Adds a header to the message, expands any HTML entities
        # and re-encodes as utf-8 before adding to the message if necessary.
        # If the message doesn't contain HTML entities, then it is just
        # added normally as 7-bit ascii
        if value.find("&#") != -1:
            # Is this, To/From/Cc ? If so, parse the addresses and
            # encode the descriptions
            if header == "To" or header == "From" or header == "Cc":
                addresses = value.split(",")
                newval = ""
                for a in addresses:
                    description, address = parse_email(a)
                    if newval != "": newval += ", "
                    newval += "\"%s\" <%s>" % (Header(
                        decode_html(description).encode("utf-8"),
                        "utf-8"), address)
                msg[header] = newval
            else:
                h = Header(decode_html(value).encode("utf-8"), "utf-8")
                msg[header] = h
        else:
            msg[header] = value

    # If the email contains HTML escape characters, switch it to being an
    # html message instead and make sure line breaks are retained
    if body.find("&#") != -1:
        contenttype = "html"
        body = body.replace("\n", "<br />")
        Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8")

    # Construct the mime message
    msg = MIMEText(body, contenttype)
    add_header(msg, "From", fromadd)
    add_header(msg, "To", toadd)
    if ccadd != "":
        add_header(msg, "Cc", ccadd)
    add_header(msg, "Subject", subject)

    # Grab the server config
    server = ""
    username = ""
    password = ""
    usetls = False
    if SMTP_SERVER is None:
        server = configuration.smtp_server(dbo)
        username = configuration.smtp_server_username(dbo)
        password = configuration.smtp_server_password(dbo)
        usetls = configuration.smtp_server_tls(dbo)
    else:
        server = SMTP_SERVER["host"]
        username = SMTP_SERVER["username"]
        password = SMTP_SERVER["password"]
        usetls = SMTP_SERVER["usetls"]

    # Construct the list of to addresses
    tolist = [strip_email(x) for x in toadd.split(",")]
    if ccadd != "":
        tolist += [strip_email(x) for x in ccadd.split(",")]

    try:
        smtp = smtplib.SMTP(server)
        if usetls:
            smtp.starttls()
        if password.strip() != "":
            smtp.login(username, password)
        fromadd = strip_email(fromadd)
        al.debug(
            "from: %s, to: %s, subject: %s, body: %s" %
            (fromadd, str(tolist), subject, body), "utils.send_email", dbo)
        smtp.sendmail(fromadd, tolist, msg.as_string())
    except Exception, err:
        al.error("%s" % str(err), "utils.send_email", dbo)
コード例 #40
0
ファイル: sendmail.py プロジェクト: zhirshya/exercise
def send_email(mailInfoFile, cnfGroup):
    #    if os.path.exists(mailInfoFile):  #'infile', type=argparse.FileType('r'), default=sys.stdin,... check for validity in the beginning?
    if os.path.exists(mailInfoFile):
        config = configparser.ConfigParser()
        config.read(mailInfoFile, encoding='utf-8')

        from_emails = config[cnfGroup]['from']
        to_emails = config[cnfGroup]['to']
        cc_emails = config[cnfGroup]['cc']
        bcc_emails = config[cnfGroup]['bcc']
        subject = config[cnfGroup]['subject']
        body = config[cnfGroup]['body']
        attachments = config[cnfGroup]['attachment']
        passwd = config[cnfGroup]['passwd']
        smtpServer = config[cnfGroup]['smtpServer']
        port = config[cnfGroup]['port']

        print('from_emails:[', from_emails, ']')
        print('to_emails:[', to_emails, ']')
        print('cc_emails:[', cc_emails, ']')
        print('bcc_emails:[', bcc_emails, ']')
        print('subject:[', subject.encode('utf-8'), ']')
        print('body:[', body.encode('utf-8'), ']')
        print('attachments:[', attachments.encode('utf-8'), ']')
        #        print('body:[', repr(body), ']')
        #        print('attachments:[', repr(attachments), ']')
        print('passwd:[', passwd, ']')
        print('smtpServer:[', smtpServer, ']')
        print('port:[', port, ']')

        msg = MIMEMultipart()
        #        msg = EmailMessage()  #python3
        msg['From'] = from_emails
        msg['To'] = to_emails
        msg['cc'] = cc_emails
        msg['bcc'] = bcc_emails
        #msg['To'] = ', '.join(to_emails)
        #msg['cc'] = ', '.join(cc_emails)
        #msg['bcc'] = ', '.join(bcc_emails)
        #https://docs.python.org/2/library/email-examples.html
        #https://docs.python.org/3/library/email.examples.html
        msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

        emails = []
        emails.append(to_emails)
        emails.append(cc_emails)
        emails.append(bcc_emails)

        msg['Date'] = formatdate(localtime=True)

        # Default encoding mode set to Quoted Printable. Acts globally!
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

        msg['Subject'] = '{}'.format(Header(subject, 'utf-8'))
        if body:
            # todo: opt for rich format such as html
            msg.attach(MIMEText(body, 'plain', 'utf-8'))

        # file name may contain ',' e.g. Pixel Recursive Super
        # Resolution,1702.00783.pdf
        attachmentList = attachments.strip().split('@')
        if attachmentList:
            try:
                for filename in attachmentList:
                    filename = filename.strip()
                    if not os.path.isfile(filename):
                        continue
                    # Guess the content type based on the file's extension.
                    # Encoding will be ignored, although we should check for
                    # simple things like gzip'd or compressed files
                    ctype, encoding = mimetypes.guess_type(filename)
                    if ctype is None or encoding is not None:
                        # No guess could be made, or the file is encoded
                        # (compressed), so use a generic bag-of-bits type.
                        ctype = 'application/octet-stream'
                    maintype, subtype = ctype.split('/', 1)
                    with open(filename, 'rb') as fp:
                        #https://docs.python.org/3/library/email.examples.html
                        #                        msg.add_attachment(
                        #                            fp.read(),
                        #                            maintype=maintype,
                        #                            subtype=subtype,
                        #                            filename=filename)

                        #https://docs.python.org/2/library/email-examples.html
                        msgAttachment = MIMEBase(maintype, subtype)
                        msgAttachment.set_payload(fp.read())
                        # Encode the payload using Base64
                        Encoders.encode_base64(msgAttachment)

                        # todo1: escape special characters in file name: & ? ! etc., already escaped(\ , \& etc.) path results error!
                        #[Errno 2] No such file or directory: u'/mnt/0/Never\\ trust\\ a\\ girl--always\\ get\\ it\\ on\\ tape\\ and\\ bring\\ backup-XFj2oDvK3m0.mkv'
                        # workaround: leave spaces in paths unquoted and use '@' to delimit files

                        #todo2: attached filenames become ATT0*
                        #msgAttachment.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(filename).encode('utf-8')))
                        msgAttachment.add_header(
                            'Content-Disposition',
                            'attachment; filename="{}"'.format(
                                os.path.basename(filename)))
                        msg.attach(msgAttachment)
            except IOError as xpt:
                # todo2: better detailed exception info
                print('except xpt:', xpt)
                print('Error opening attachment file "{}"'.format(
                    filename.encode('utf-8')))
                print('os.path.basename(filename):{}'.format(
                    os.path.basename(filename).encode('utf-8')))
                sys.exit(1)

        print('type(port):', type(port))

        smtpObj = smtplib.SMTP(smtpServer, port.encode('ascii', 'ignore'))
        smtpObj.set_debuglevel(1)
        #Set the debug output level. A value of 1 or True for level results in debug messages for connection and for all messages sent to and received from the server. A value of 2 for level results in these messages being timestamped.
        #Changed in version 3.5: Added debuglevel 2.
        #https://docs.python.org/3/library/smtplib.html

        smtpObj.ehlo()
        smtpObj.starttls()
        #SMTP.starttls([keyfile[, certfile]])
        #Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.
        #https://docs.python.org/2/library/smtplib.html
        #SMTP.starttls(keyfile=None, certfile=None, context=None)
        #Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.
        #https://docs.python.org/3/library/smtplib.html

        smtpObj.ehlo()
        smtpObj.login(from_emails, passwd)
        smtpObj.sendmail(from_emails, emails, msg.as_string())
        smtpObj.quit()
    else:
        print('Config file not found! Exiting!')
        sys.exit(1)
コード例 #41
0
    ESMTPSenderFactory = ESMTPSenderFactory  # for pyflakes
except ImportError:
    ESMTPSenderFactory = None

have_ssl = True
try:
    from twisted.internet import ssl
    from OpenSSL.SSL import SSLv3_METHOD
except ImportError:
    have_ssl = False

# this incantation teaches email to output utf-8 using 7- or 8-bit encoding,
# although it has no effect before python-2.7.
from email import Charset

Charset.add_charset('utf-8', Charset.SHORTEST, None, 'utf-8')

from buildbot import config
from buildbot import interfaces
from buildbot import util
from buildbot.process.users import users
from buildbot.status import base
from buildbot.status.results import EXCEPTION
from buildbot.status.results import FAILURE
from buildbot.status.results import Results
from buildbot.status.results import SUCCESS
from buildbot.status.results import WARNINGS

# Email parsing can be complex. We try to take a very liberal
# approach. The local part of an email address matches ANY non
# whitespace character. Rather allow a malformed email address than