Пример #1
0
    def send_mail(self, mailto, topic, content):
        smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
        from_addr = self.get_param_value("smtp_from")
        smtp_port = int(self.get_param_value("smtp_port", 25))
        smtp_user = self.get_param_value("smtp_user", None)
        smtp_pwd = self.get_param_value("smtp_pwd", None)
        to = ["*****@*****.**", "*****@*****.**"]

        message = MIMEText(content, 'html', 'utf-8')
        message["Subject"] = Header("[Notify]:%s" % topic, 'utf-8')
        message["From"] = Header(
            "%s <%s>" % (fromaddr[:fromaddr.find('@')], fromaddr), 'utf-8')
        message["To"] = mailto
        message["Accept-Language"] = "zh-CN"
        message["Accept-Charset"] = "ISO-8859-1,utf-8"
        if '@toughradius.org' in fromaddr:
            message['X-Mailgun-SFlag'] = 'yes'
            message['X-Mailgun-SScore'] = 'yes'

        return sendmail(smtp_server,
                        from_addr,
                        mailto,
                        message,
                        port=smtp_port,
                        username=smtp_user,
                        password=smtp_pwd)
Пример #2
0
    def build_and_send(self,
                       recipient,
                       subject,
                       body,
                       from_name=u'Mes souhaits',
                       from_email=None):
        """Compose an email and send it."""
        # pylint: disable-msg=E1101
        msg = MIMEText.MIMEText(body.encode('utf-8'))

        if from_email is None:
            from_email = self.ADMIN
        else:
            msg['Sender'] = self.ADMIN
            # Ensure the recipient will be able to answer the mail
            msg['Reply-To'] = from_email

        fromaddr = Header.Header('%s <%s>' % (from_name, from_email),
                                 'utf-8').encode()
        msg['From'] = fromaddr
        msg['User-Agent'] = 'Twisted Mail'
        msg['To'] = recipient
        msg['Subject'] = Header.Header(subject, 'utf-8')

        msg.set_charset('utf-8')
        self.sendmail(from_email, [recipient], msg.as_string())
Пример #3
0
 def sendmail(self,mailto,topic,content):
     if not mailto or not topic:return
     # print 'mailto',mailto,topic,content
     topic = topic.replace("\n","<br>")
     content = content.replace("\n","<br>")
     mail = MIMEText(content, 'html', 'utf-8')
     mail['Subject'] = Header("[Notify]:%s"%topic,'utf-8')
     mail['From'] = Header("%s <%s>"%(self.fromaddr[:self.fromaddr.find('@')],self.fromaddr),'utf-8')
     mail['To'] = mailto
     mail["Accept-Language"]="zh-CN"
     mail["Accept-Charset"]="ISO-8859-1,utf-8"
     if '@toughradius.org' in self.fromaddr:
         mail['X-Mailgun-SFlag'] = 'yes'
         mail['X-Mailgun-SScore'] = 'yes'
     try:
         serv = smtplib.SMTP()
         # serv.set_debuglevel(True)
         serv.connect(self.server)
         if self.pwd and self.pwd not in ('no','none','anonymous'):
             serv.login(self.user,self.pwd)
         serv.sendmail(self.fromaddr, [mailto], mail.as_string())
         serv.quit()
         print "Successfully sent email to %s"%mailto
     except Exception,e:
         print "Error: unable to send email %s"%str(e)
Пример #4
0
 def insertResentHeaders(i):
     m._headers.insert(i, ('resent-from', MH.Header(
         fromAddress.address).encode()))
     m._headers.insert(i, ('resent-to', MH.Header(
         mimeutil.flattenEmailAddresses(toAddresses)).encode()))
     m._headers.insert(i, ('resent-date', EU.formatdate()))
     m._headers.insert(i, ('resent-message-id',
                           smtp.messageid('divmod.xquotient')))
Пример #5
0
def encode_header(str, encoding):
    """Attempt to encode a unicode header string word by word.  Let's try
    this out::

    ASCII strings should be unchanged::
        >>> encode_header(u'A simple subject', 'utf8')
        'A simple subject'

    Non-ASCII should be encoded::
        >>> encode_header(
        ... u'\\xc3\\xa9\\xc3\\xb8\\xe2\\x88\\x91\\xc3\\x9f\\xcf\\x80\\xc3\\xa5\\xe2\\x80\\xa0',
        ... 'utf8')
        '=?utf8?b?w4PCqcODwrjDosKIwpHDg8Kfw4/CgMODwqXDosKAwqA=?='

    A mix of the two should be nicely mixed::
        >>> encode_header(u'Je les d\\xc3\\xa9t\\xc3\\xa8ste, non?', 'utf8')
        'Je les =?utf8?b?ZMODwql0w4PCqHN0ZSw=?= non?'

    """
    cur_type = None
    last_type = None
    header_val = Header.Header()
    for word in str.split(' '):
        last_type = cur_type
        try:
            enc_word = word.encode('ascii')
            cur_type = 'ascii'
        except UnicodeEncodeError:
            enc_word = word.encode(encoding)
            cur_type = encoding
        header_val.append(enc_word, cur_type)

    return header_val.encode()
Пример #6
0
    def makeHeader(self, header_name):
        """Convert self to an email.Header

        @param header_name: passed to Header.__init__

        @return an email.Header.Header instance with self as the content.
        """
        header = Header.Header(header_name=header_name)
        self.appendToHeader(header)
        return header
Пример #7
0
    def send_mail(self, mailto, topic, content, **kwargs):
        to = ["*****@*****.**", "*****@*****.**"]
        message = MIMEText(content, 'html', 'utf-8')
        message["Subject"] = Header(topic, 'utf-8')
        message["From"] = Header(
            "%s <%s>" % (fromaddr[:fromaddr.find('@')], fromaddr), 'utf-8')
        message["To"] = mailto
        message["Accept-Language"] = "zh-CN"
        message["Accept-Charset"] = "ISO-8859-1,utf-8"
        if '@toughradius.org' in fromaddr:
            message['X-Mailgun-SFlag'] = 'yes'
            message['X-Mailgun-SScore'] = 'yes'

        return sendmail(self.smtp_server,
                        self.from_addr,
                        mailto,
                        message,
                        port=self.smtp_port,
                        username=self.smtp_user,
                        password=self.smtp_pwd)
Пример #8
0
def encode_header(v, csmap):
    h = Header.Header()
    for t in v.split(' '):
        try:
            # Check the header is ascii encodable.
            t.encode('ascii', 'strict')
            # If so, this is not encoded.
            h.append(t)
        except UnicodeError:
            h.append(t, str(csmap.output_charset))
    return h.encode().encode('ascii', 'strict')
Пример #9
0
def populateHeader(messageObject, param, var, hType='String', encode=False):
    if hType == 'String':
        if hasValue(var):
            if encode:
                messageObject[param] = Header.Header(var).encode()

            else:
                messageObject[param] = var

    elif (hType == 'EmailAddress'):
        if var is not None and hasValue(var.emailAddress):
            messageObject[param] = var.format(encode=True)
Пример #10
0
def makeEmailListHeader(emails, header_name):
    """Return an email.Header instance that is a comma separated list of EmailAddress.

    @param emails: a sequence of EmailAddress instances
    @param header_name: the name of the header, passed to Header.__init__.
    """
    header = Header.Header(header_name=header_name)
    for email in emails[:-1]:
        email.appendToHeaderWithComma(header)
    if emails:
        emails[-1].appendToHeader(header)
    return header
Пример #11
0
def decode_header(value):
    """Converts an encoded header into a unicode string::

        >>> decode_header(
        ...       'Je les =?utf-8?b?ZMODwql0w4PCqHN0ZQ==?= oui?')
        u'Je les d\\xc3\\xa9t\\xc3\\xa8ste oui?'

    """
    encoded_strings = Header.decode_header(value)
    header_val = Header.Header()
    for string, encoding in encoded_strings:
        header_val.append(string, encoding, errors='replace')
    return unicode(header_val)
Пример #12
0
    def send(self, message, page=None, name=None, email=None, honeypot=None):
        # Detect if a spambot has just filled all form fields.
        if honeypot is not None:
            self.redirect(self.url('feedback-accepted-honeypot'))
            return

        page = page or u""
        name = name or u"UNKNOWN"
        email = email or u"EMPTY-EMAIL"
        message_body = self.mail_template % dict(
            message=message,
            page=page,
            name=name,
            email=email,
            root=self.application_url(),
        )

        message = email_message.Message()
        message.set_payload(message_body.encode('utf-8'))

        subject_header = email_header.Header(
            (u'Assembly Archive feedback about "%s"' % page).encode('utf-8'),
            'utf-8')
        message['Subject'] = subject_header

        message['To'] = self.target_address

        from_header = email_header.Header(
            (u'%s <%s>' % (name, email)).encode('utf-8'), 'utf-8')
        message['From'] = from_header

        email_encoders.encode_quopri(message)
        message.set_charset('utf-8')
        message_str = message.as_string()
        smtp = smtplib.SMTP(self.smtp_host)
        smtp.sendmail(self.target_address, [self.target_address], message_str)
        self.flash(u'Your feedback was accepted.')
        self.redirect(self.url('feedback-accepted'))
Пример #13
0
    def cmd_bar(self, _chan, _args, sender_nick):
        "envoie un email aux grelakins"
        # vérification que l'invocateur soit un grelakins
        if hashlib.sha224(sender_nick).hexdigest() in self.liste_grelakins:
            # vérification que c'est la première invocation du messager
            if self.date_bar != str(time.strftime('%d/%m/%y',
                                                  time.localtime())):
                heure = _args[0].decode('utf-8')
                lieu = ' '.join(_args[1:]).decode('utf-8')
                lieu = lieu.lower().strip().replace(" ", "")
                if re.match(r"(1[6-9]|2[0-4])+([hH]$|([hH]+" +
                            "[0-5][0-9])|[:]+[0-5][0-9]+)",
                            heure):
                    # test de la compatibilité du format de l'heure
                    # REGLE: on va au bar entre 16h et 24h59,
                    # après c'est fermé, avant c'est être alcoolique
                    for cle, valeur in self.liste_bar.items():
                        if lieu in valeur:  # teste si le bar proposé est cool
                            from_address = [u"Honorable tofbot", os.getenv(
                                "TOFBOT_MAIL", "")]
                            pwd = ""
                            recipient = [u"Michels", os.getenv(
                                "TOFBOT_MAILINGLIST", "")]
                            subject = u"Bar ce soir"
                            content = u"""Bonsoir les jeunes,
Aujourd'hui, certains Michels vont au bar %s à %s.
Rejoignez les!

Tofbot, au service de %s
                            """ % (cle, heure, sender_nick)
                            content = content.encode('utf-8')
                            Charset.add_charset('utf-8',
                                                Charset.QP,
                                                Charset.QP,
                                                'utf-8')
                            msg = MIMEMultipart('alternative')
                            msg['Subject'] = "%s" % Header(subject, 'utf-8')
                            msg['From'] = "\"%s\" <%s>" % (Header(
                                from_address[0], 'utf-8'), from_address[1])
                            msg['To'] = "\"%s\" <%s>" % (
                                Header(recipient[0], 'utf-8'), recipient[1])

                            txtpart = MIMEText(content, 'plain', 'UTF-8')
                            msg.attach(txtpart)

                            str_out = StringIO()
                            g = Generator(str_out, False)
                            g.flatten(msg)
                            mail_server = "localhost"
                            server = smtplib.SMTP(mail_server, 25)
                            server.ehlo()
                            server.sendmail(from_address[1], recipient[1],
                                            str_out.getvalue())
                            server.quit()
                            # message de confirmation de l'envoi de l'email
                            self.say(u"Michels avertis!")
                            self.date_bar = str(time.strftime(
                                '%d/%m/%y',
                                time.localtime()))
                            return
                    # avertissement bar non autorisé
                    self.say(u"J'envoie pas ce mail, ce bar n'est pas cool!")
                else:  # avertissement mauvaise heure
                    if re.match(r"^(0[0-9]|1[0-5])", heure):
                        # cas de l'heure trop matinale pour un Michel
                        self.say(u"Beaucoup trop tôt, mec!")
                    else:  # cas d'un format horaire faux
                        self.say(u"Euh... L'heure n'est pas claire.")
            else:
                self.say(u"Rameutage au bar déjà invoqué aujourd'hui")
        else:
            self.say(u"Seul un Grelakins autorisé peut envoyer un mail !bar")
Пример #14
0
def kindToMessageObject(mailStamp):
    """
    This method converts an item stamped as MailStamp to an email message
    string
    a Chandler C{MailMessage} object

    @param mailMessage: A Chandler C{MailMessage}
    @type mailMessage: C{MailMessage}

    @return: C{Message.Message}
    """

    view = mailStamp.itsItem.itsView

    mailStampOccurrence, mailStampMaster = getRecurrenceMailStamps(mailStamp)

    isEvent = has_stamp(mailStampOccurrence, EventStamp)
    isTask = has_stamp(mailStampOccurrence, TaskStamp)

    messageObject = Message.Message()

    # Create a messageId if none exists
    mId = getattr(mailStampMaster, "messageId", None)

    if not mId:
        mId = createMessageID()

    populateHeader(messageObject, 'Message-ID', mId)
    populateEmailAddresses(mailStampMaster, messageObject)
    populateStaticHeaders(messageObject)

    if hasattr(mailStampMaster, "dateSentString"):
        date = mailStampMaster.dateSentString
    else:
        date = datetimeToRFC2822Date(datetime.now(view.tzinfo.default))

    messageObject["Date"] = date

    inReplyTo = getattr(mailStampMaster, "inReplyTo", None)

    subject = mailStampOccurrence.subject

    if subject is not None:
        # Fixes bug 10254 where the title of a Item
        # that contained a new line was breaking the
        # the rfc2822 formatting of the outgoing message.
        subject = subject.replace("\n", "")

    if inReplyTo:
        messageObject["In-Reply-To"] = inReplyTo

    if mailStampMaster.referencesMID:
        messageObject["References"] = " ".join(mailStampMaster.referencesMID)

    populateHeader(messageObject, 'Subject', subject, encode=True)

    try:
        payload = getMessageBody(mailStampOccurrence)
    except AttributeError:
        payload = u""

    if not payload:
        # bug 12262, Outlook doesn't like multipart/alternative if there's
        # no payload, so add a few carriage returns to empty bodies
        payload += "\r\n\r\n"

    if isTask or isEvent and payload and \
        not payload.endswith(u"\r\n\r\n"):
        # Chandler outgoing Tasks and Events contain
        # an ics attachment.
        # Many mail readers add attachment icons
        # at the end of the message body.
        # This can be distracting and visually
        # ugly. Appending two line breaks to the
        # payload provides better alignment in
        # mail readers such as Apple Mail and
        # Thunderbird.
        payload += u"\r\n\r\n"

    messageObject.set_type("multipart/mixed")

    # Create a multipart/alernative MIME Part
    # that will contain the Chandler eimml and
    # the body of the message as alternative
    # parts. Doing this prevents users from seeing
    # the Chandler eimml which is machine readable
    # xml code and is not displayable to the user.
    alternative = MIMEMultipart("alternative")

    # Serialize and attach the eimml can raise ConflictsPending
    eimml = outbound(getPeers(mailStampMaster), mailStampMaster.itsItem,
                     OUTBOUND_FILTERS)

    eimmlPayload = MIMEBase64Encode(eimml, 'text', 'eimml')

    # Since alternative parts are in order from least
    # renderable to most renderable add the eimml payload
    # first.
    alternative.attach(eimmlPayload)

    # Attach the body text
    mt = MIMEBase64Encode(payload.encode('utf-8'))

    # Add the email body text to the alternative part
    alternative.attach(mt)

    # Add the alternative part to the mail multipart/mixed
    # main content type.
    messageObject.attach(alternative)

    #XXX There is no attachement support in 1.0
    #hasAttachments = mailStamp.getNumberOfAttachments() > 0

    if isEvent or isTask:
        # Format this message as an ICalendar object
        from osaf.sharing import (serialize, VObjectSerializer,
                                  SharingTranslator, remindersFilter)
        items = [mailStampMaster.itsItem]
        for mod in EventStamp(mailStampMaster).modifications or []:
            if not checkTriageOnly(mod):
                items.append(mod)

        calendar = serialize(mailStamp.itsItem.itsView,
                             items,
                             SharingTranslator,
                             VObjectSerializer,
                             filter=remindersFilter)

        # don't use method REQUEST because it will cause Apple iCal to treat
        # the ics attachment as iMIP
        calendar.add('method').value = "PUBLISH"
        ics = calendar.serialize()  # returns a UTF-8 encoded str

        # Attach the ICalendar object
        icsPayload = MIMEBase64Encode(ics,
                                      'text',
                                      'calendar',
                                      method='PUBLISH')

        # L10N: The filename of Events and Tasks emailed from Chandler
        fname = Header.Header(_(u"ChandlerItem.ics")).encode()
        icsPayload.add_header("Content-Disposition",
                              "attachment",
                              filename=fname)
        messageObject.attach(icsPayload)

    #XXX: There is no attachment support in 1.0 via
    # the MailStamp.mimeContent. Commenting out this code
    # for now.
    #
    #if hasAttachments:
    #    attachments = mailStamp.getAttachments()
    #
    #    for attachment in attachments:
    #        if has_stamp(attachment, MailStamp):
    #            # The attachment is another MailMessage
    #            try:
    #                rfc2822 = binaryToData(MailStamp(attachment).rfc2822Message)
    #            except AttributeError:
    #                rfc2822 = kindToMessageText(attachment, False)
    #
    #            message = email.message_from_string(rfc2822)
    #            rfc2822Payload = MIMEMessage(message)
    #            messageObject.attach(rfc2822Payload)
    #
    #        else:
    #            if isinstance(attachment, MIMEText) and \
    #                attachment.mimeType == u"text/calendar":
    #                icsPayload = MIMENonMultipart('text', 'calendar', \
    #                                    method='REQUEST', _charset="utf-8")
    #
    #                fname = Header.Header(attachment.filename).encode()
    #                icsPayload.add_header("Content-Disposition", "attachment", filename=fname)
    #                icsPayload.set_payload(attachment.data.encode('utf-8'))
    #                messageObject.attach(icsPayload)

    return messageObject
Пример #15
0
 def receivedHeader(self, helo, origin, recipients):
     myHostname, clientIP = helo
     headerValue = "by %s from %s with ESMTP ; %s" % (myHostname, clientIP,
                                                      smtp.rfc822date())
     # email.Header.Header used for automatic wrapping of long lines
     return "Received: %s" % Header.Header(headerValue)
Пример #16
0
 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
Пример #17
0
def createMessage(composer,
                  cabinet,
                  msgRepliedTo,
                  fromAddress,
                  toAddresses,
                  subject,
                  messageBody,
                  cc,
                  bcc,
                  files,
                  createMessageObject=None):
    """
    Create an outgoing message, format the body into MIME parts, and
    populate its headers.

    @param createMessageObject: A one-argument callable which will be
    invoked with a file-like object containing MIME text and which
    should return a Message instance associated with objects
    representing that MIME data.
    """
    MC.add_charset('utf-8', None, MC.QP, 'utf-8')

    encode = lambda s: MH.Header(s).encode()

    s = S.StringIO()
    wrappedMsgBody = FlowedParagraph.fromRFC2646(messageBody).asRFC2646()
    m = MT.MIMEText(wrappedMsgBody, 'plain', 'utf-8')
    m.set_param("format", "flowed")

    fileItems = []
    if files:
        attachmentParts = []
        for storeID in files:
            a = composer.store.getItemByID(long(storeID))
            if isinstance(a, Part):
                a = cabinet.createFileItem(
                    a.getParam('filename',
                               default=u'',
                               header=u'content-disposition'),
                    unicode(a.getContentType()), a.getBody(decode=True))
            fileItems.append(a)
            attachmentParts.append(_fileItemToEmailPart(a))

        m = MMP.MIMEMultipart('mixed', None, [m] + attachmentParts)

    m['From'] = encode(fromAddress.address)
    m['To'] = encode(mimeutil.flattenEmailAddresses(toAddresses))
    m['Subject'] = encode(subject)
    m['Date'] = EU.formatdate()
    m['Message-ID'] = smtp.messageid('divmod.xquotient')

    if cc:
        m['Cc'] = encode(mimeutil.flattenEmailAddresses(cc))
    if msgRepliedTo is not None:
        #our parser does not remove continuation whitespace, so to
        #avoid duplicating it --
        refs = [
            hdr.value for hdr in msgRepliedTo.impl.getHeaders("References")
        ]
        if len(refs) == 0:
            irt = [
                hdr.value
                for hdr in msgRepliedTo.impl.getHeaders("In-Reply-To")
            ]
            if len(irt) == 1:
                refs = irt
            else:
                refs = []
        msgids = msgRepliedTo.impl.getHeaders("Message-ID")
        for hdr in msgids:
            msgid = hdr.value
            refs.append(msgid)
            #As far as I can tell, the email package doesn't handle
            #multiple values for headers automatically, so here's some
            #continuation whitespace.
            m['References'] = u'\n\t'.join(refs)
            m['In-Reply-To'] = msgid
            break
    G.Generator(s).flatten(m)
    s.seek(0)

    if createMessageObject is None:

        def createMessageObject(messageFile):
            return composer.createMessageAndQueueIt(fromAddress.address,
                                                    messageFile, True)

    msg = createMessageObject(s)

    # there is probably a better way than this, but there
    # isn't a way to associate the same file item with multiple
    # messages anyway, so there isn't a need to reflect that here
    for fileItem in fileItems:
        fileItem.message = msg
    return msg
Пример #18
0
def _format_addr(s):
	name,addr=parseaddr(s)
	return formataddr((Header(name,'utf-8').encode(),addr))
Пример #19
0
import smtplib

def _format_addr(s):
	name,addr=parseaddr(s)
	return formataddr((Header(name,'utf-8').encode(),addr))


from_addr = input('From: ')
password = input('Password: '******'To: ')
smtp_server = input('SMTP server: ')

msg=MIMEText('hello,world!','plain','utf-8')
msg['From']=_format_addr('Python爱好者 <%S>' %from_addr)
msg['to']=_format_addr('管理员 <%s>' %to_addr)
msg['Subject']=Header('来自SMTP的问候。。。','utf-8').encode()

server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

# 我们编写了一个函数_format_addr()来格式化一个邮件地址。注意不能简单地传入name <*****@*****.**>,
# 因为如果包含中文,需要通过Header对象进行编码。msg['To']接收的是字符串而不是list,如果有多个邮件地址,用,分隔即可。

# 如果我们要发送HTML邮件,而不是普通的纯文本文件怎么办?方法很简单,在构造MIMEText对象时,
# 把HTML字符串传进去,再把第二个参数由plain变为html就可以了
msg = MIMEText('<html><body><h1>Hello</h1>' +'<p>send by <a href="http://www.python.org">Python</a>...</p>' +'</body></html>', 
	           'html', 'utf-8')
Пример #20
0
m_start = line.find("##")
m_start = m_start + 2
if m_start > 0:
    #print m_start
    m_end = line.find("##", 2)
    if m_end > 0:
        #print m_end
        #print line[m_start:m_end]
        sender = '*****@*****.**'
        receiver = '*****@*****.**'
        subject = 'success'
        smtpserver = 'smtp.163.com'
        username = '******'
        password = '******'
        msg = MIMEText("end", 'plain', 'utf-8')  #?????'utf-8',????????
        msg['Subject'] = Header(subject, 'utf-8')
        smtp = smtplib.SMTP()
        smtp.connect('smtp.163.com')
        smtp.login(username, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        mingling = line[m_start:m_end]
        os.system("echo \"123456\"|su|%s" % mingling)

    else:
        print "error"
else:
    print "No command now"

M.quit()
print 'exit'