Пример #1
0
    def update(self):
        super(SendNewsletter, self).update()

        if 'form.send' in self.request:
            subs = ISubscribersManagement(self.context.__parent__)

            emails = []
            for principal in subs.getSubscribers():
                mail = IMailAddress(principal, None)
                if mail is not None:
                    email = mail.address

                    if email:
                        emails.append(
                            formataddr((principal.title or principal.id, email)))

            if emails:
                message = self.generateMessage()
                message['Subject'] = make_header(((self.context.title, 'utf-8'),))

                mailer = getUtility(IMailer)

                from_address = str(formataddr(
                    (mailer.email_from_name, mailer.email_from_address)))

                message['From'] = from_address
                mailer.send(from_address, emails, message.as_string())

                IStatusMessage(self.request).add(_('Newsletter has been sent.'))
Пример #2
0
def sendNotification(types, *objects, **params):
    template = queryMultiAdapter(
        (tuple(objects) + (getRequest(),)), INotificationMailTemplate)
    if template is None:
        return

    principals = getSubscribers(types, *objects, **params)

    if principals:
        emails = set()
        for principal in getPrincipals(principals):
            mail = IMailAddress(principal, None)
            if mail is not None:
                emails.add(formataddr((principal.title, mail.address)))

        if emails:
            template.update()

            configlet = getUtility(IContentNotifications)
            if not template.hasHeader('Reply-to'):
                template.addHeader('Reply-to', formataddr((configlet.notification_replyto_name, configlet.notification_replyto_address),), False)
            if not template.hasHeader('From'):
                template.addHeader('From', formataddr((configlet.notification_from_name, configlet.notification_from_address),))

            template.send(emails)

    return principals
Пример #3
0
    def update(self):
        super(CommentNotificationMail, self).update()

        content = self.context
        comment = self.context0
        self.comment = comment

        request = self.request

        principal = self.request.principal

        mailer = getUtility(IMailer)

        profile = IPersonalProfile(principal, None)
        if profile is not None and profile.email:
            author = profile.title
            self.author = author
            space = getattr(profile, 'space', None)
            if space is not None:
                self.profile_url = '%s/profile/' % absoluteURL(space, request)
            self.addHeader(u'To', formataddr((author, profile.email),))
            self.addHeader(u'From', formataddr((author, mailer.email_from_address),))
        else:
            self.author = principal.title or principal.id

        view = queryMultiAdapter((content, request), IContentViewView)
        if view is not None:
            self.url = '%s/%s'%(absoluteURL(content, request), view.name)
        else:
            self.url = '%s/'%absoluteURL(content, request)

        self.content = comment.content
        self.portal_title = getMultiAdapter((getSite(), request), IBreadcrumb).name
        self.available = comment.isAvailable()
Пример #4
0
    def update(self):
        super(NotificationMail, self).update()

        content = self.context
        event = self.contexts[0]
        request = self.request

        self.url = "%s/" % absoluteURL(content, request)

        principal = IOwnership(content).owner

        profile = IPersonalProfile(principal)
        if profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u"From", formataddr((author, profile.email)))
            self.addHeader(u"To", formataddr((self.author, profile.email)))
        else:
            self.author = principal.title or principal.id

        self.site = getSite()

        if profile.space is not None:
            self.space = u"%s/" % absoluteURL(profile.space, request)

        cId = getUtility(IIntIds).getId(content)

        self.messageId = u"<*****@*****.**>" % (cId, time.time())
Пример #5
0
def send_email(sender, recipient, subject, body):
   from smtplib import SMTP
   from email.MIMEText import MIMEText
   from email.Header import Header
   from email.Utils import parseaddr, formataddr
   # Header class is smart enough to try US-ASCII, then the charset we
   # provide, then fall back to UTF-8.
   header_charset = 'ISO-8859-1'
   # We must choose the body charset manually
   for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII'  :
      try:
         body.encode(body_charset)
      except UnicodeError:
         pass
      else:
         break
   # Split real name (which is optional) and email address parts
   sender_name, sender_addr = parseaddr(sender)
   recipient_name, recipient_addr = parseaddr(recipient)
   # We must always pass Unicode strings to Header, otherwise it will
   # use RFC 2047 encoding even on plain ASCII strings.
   sender_name = str(Header(unicode(sender_name), header_charset))
   recipient_name = str(Header(unicode(recipient_name), header_charset))
   # Make sure email addresses do not contain non-ASCII characters
   sender_addr = sender_addr.encode('ascii')
   recipient_addr = recipient_addr.encode('ascii')
   # Create the message ('plain' stands for Content-Type: text/plain)
   msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
   msg['From'] = formataddr((sender_name, sender_addr))
   msg['To'] = formataddr((recipient_name, recipient_addr))
   msg['Subject'] = Header(unicode(subject), header_charset)
   # Send the message via SMTP to localhost:25
   smtp = SMTP("localhost")
   smtp.sendmail(sender, recipient, msg.as_string())
   smtp.quit()
Пример #6
0
 def send(self, email_to, email_subject, email_content, is_dry=False):
     """
         is_dry为true时,不执行,仅仅sleep
     """
     if is_dry:
         time.sleep(10)
     else:
         msg = MIMEMultipart()
         at = email_to.find("@")
         if at <= 0: return
         domain = email_to[at+1:].strip()
         if domain not in NOT_SUPPORT_UTF8_DOMAIN:
             enc = "utf-8"
         else:
             enc = "gb18030"
         if enc.lower() != "utf-8":
             print enc
             self.email_from = self.ignore_encode(self.email_from, enc) 
             email_to = self.ignore_encode(email_to, enc)
             email_content = self.ignore_encode(email_content, enc)
             email_subject = self.ignore_encode(email_subject, enc)
         #msg = MIMEMultipart()
         msg = MIMEText(email_content, _subtype="plain",  _charset=enc)
         msg['Subject'] = Header(email_subject, enc) 
         fname = str(Header(self.email_from, enc))
         msg['From'] = formataddr((fname, self.email_from))
         tname = str(Header(email_to, enc))
         msg['To'] = formataddr((tname, email_to))
         print (self.email_from, email_to, msg)
         errs = ""
         errs = self.sendSvr.sendmail(self.email_from, email_to, msg.as_string())
         assert len(errs) == 0
Пример #7
0
def send_email(body, subject, recipient):
    import smtplib
    from smtplib import SMTP
    from email.MIMEText import MIMEText
    from email.Header import Header
    from email.Utils import parseaddr, formataddr
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    localhost port 25.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """

    sender = '*****@*****.**'
    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), 'html', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    # Create server object with SSL option
    server = smtplib.SMTP_SSL('smtp.{{service provider}}.com', 465)

    # Perform operations via server
    server.login(sender, '{pass}')
    server.sendmail(sender, [recipient], msg.as_string())
    server.quit()
Пример #8
0
    def update(self):
        super(TaskDeletedNotification, self).update()

        context = removeAllProxies(self.context)
        request = self.request
        principal = self.request.principal

        self.name = context.__name__

        mailer = getUtility(IMailer)

        profile = IPersonalProfile(principal, None)
        if profile is not None and profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u"To", formataddr((author, profile.email)))
        else:
            self.author = principal.title or principal.id

        self.addHeader(u"From", formataddr((self.author, mailer.email_from_address)))

        self.url = "%s/" % absoluteURL(context, request)
        self.project = context.__parent__.__parent__

        # project
        self.projectTitle = self.project.title
        self.projectUrl = u"%s/" % absoluteURL(self.project, request)
Пример #9
0
def sendmail(message, email, tweeter,date ):
	header_charset = 'ISO-8859-1'

	for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
		try:
			message.encode(body_charset)
		except UnicodeError:
			pass
		else:
			break
	subject="[tweet2email] "+tweeter
	sender_name = str(Header(unicode('tweet2email'), header_charset))
	sender_addr = str(Header(unicode('tweet2email@localhost'), header_charset))
	recipient_name = str(Header(unicode(email), header_charset))
	recipient_addr = str(Header(unicode(email), header_charset))
	sender_addr = sender_addr.encode('ascii')
	recipient_addr = recipient_addr.encode('ascii')
	msg = MIMEText(message.encode(body_charset), 'plain', body_charset)
	msg['From'] = formataddr((sender_name, sender_addr))
	msg['To'] = formataddr((recipient_name, recipient_addr))
	msg['Subject'] = Header(unicode(subject), header_charset)
	if date:
		cell=date.split()
		date=cell[0]+', '+cell[2]+' '+cell[1]+' '+cell[5]+' '+cell[3]+ ' '+cell[4]
		msg['Date'] = Header(unicode(date), header_charset)
	smtp = smtplib.SMTP("localhost")
	smtp.sendmail(sender_addr, recipient_addr, msg.as_string())
	smtp.quit()
Пример #10
0
def sendEmail(server, port, login, password, sender, recipient, subject, body):
    """Send e-mail function with unicode support"""
    headerCharset = "ISO-8859-1"

    for bodyCharset in ("US-ASCII", "ISO-8859-1", "UTF-8"):
        try:
            body.encode(bodyCharset)

        except UnicodeError:
            pass

        else:
            break

    senderName, senderAddr = parseaddr(sender)
    recipientName, recipientAddr = parseaddr(recipient)

    senderName = str(Header(unicode(senderName), headerCharset))
    recipientName = str(Header(unicode(recipientName), headerCharset))

    senderAddr = senderAddr.encode("ascii")
    recipientAddr = recipientAddr.encode("ascii")

    msg = MIMEText(body.encode(bodyCharset), "html", bodyCharset)
    msg["From"] = formataddr((senderName, senderAddr))
    msg["To"] = formataddr((recipientName, recipientAddr))
    msg["Subject"] = Header(unicode(subject), headerCharset)

    server = smtplib.SMTP(server, port)
    server.login(login, password)
    server.sendmail(sender, recipient, msg.as_string())
    server.quit()
Пример #11
0
    def update(self):
        super(EventDeletedNotification, self).update()

        context = removeAllProxies(self.context)
        request = self.request
        principal = self.request.principal

        self.name = context.__name__

        mailer = getUtility(IMailer)

        profile = IPersonalProfile(principal, None)
        if profile is not None and profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u'To', formataddr((author, profile.email),))
        else:
            self.author = principal.title or principal.id

        self.addHeader(u'From', formataddr((self.author, mailer.email_from_address),))

        self.url = '%s/'%absoluteURL(context, request)
        self.calendar = context.__parent__

        # calendar
        self.calendarUrl = u'%s/'%absoluteURL(self.calendar, request)
Пример #12
0
def _send(fromname, fromaddr, name, address, subject, html):

    header_charset = 'ISO-8859-1'

    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            html.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    sender_name = str(Header(unicode(fromname), header_charset))
    recipient_name = str(Header(unicode(name), header_charset))
    fromaddr = fromaddr.encode('ascii')
    address = address.encode('ascii')
    msg = MIMEMultipart('alternative')
    msg['From'] = formataddr((sender_name, fromaddr))
    msg['To'] = formataddr((recipient_name, address))
    msg['Subject'] = Header(unicode(subject), header_charset)
    part1 = MIMEText(html2text(html).encode(body_charset), 'plain', body_charset)
    part2 = MIMEText(('<html><head></head><body>%s</body></html>' % html).encode(body_charset), 'html', body_charset)
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('smtp.gmail.com', 587, DB.Vars.site, 20)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(DB.Vars.mailuser, DB.Vars.mailpwd)
    s.sendmail(fromaddr, address, msg.as_string())
    s.quit()
    print "Sent welcome mail to", address, 'from', fromaddr
Пример #13
0
def send_email(sender, recipient, subject, body, host='localhost', port='25', username=None, password=None, header_charset='UTF-8'):
 
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    smtp = SMTP('{host}:{port}'.format(host=host, port=port))
    smtp.starttls()
    if username and password:
        smtp.login(username,password)
    smtp.sendmail(sender, recipient, msg.as_string())
    smtp.quit()
Пример #14
0
    def send(self):
        body = self.template.render(**self.vars)

        header_charset = 'ISO-8859-1'
        body_charset = 'UTF-8'

        sender_name, sender_addr = parseaddr(self.sender)
        recipient_name, recipient_addr = parseaddr(self.recipient)

        # We must always pass Unicode strings to Header, otherwise it will
        # use RFC 2047 encoding even on plain ASCII strings.
        sender_name = str(Header(unicode(sender_name), header_charset))
        recipient_name = str(Header(unicode(recipient_name), header_charset))

        # Make sure email addresses do not contain non-ASCII characters
        sender_addr = sender_addr.encode('ascii')
        recipient_addr = recipient_addr.encode('ascii')

        # Create the message ('plain' stands for Content-Type: text/plain)
        msg = MIMEText(body, 'plain', body_charset)
        msg['From'] = formataddr((sender_name, sender_addr))
        msg['To'] = formataddr((recipient_name, recipient_addr))
        msg['Subject'] = Header(unicode(self.subject), header_charset)

        with SMTP() as smtp:
            smtp.connect(self.smtp)
            smtp.sendmail(self.sender, self.recipient, msg.as_string())
Пример #15
0
Файл: mail.py Проект: mcr/ietfdb
def send_mail_mime(request, to, frm, subject, msg, cc=None, extra=None, toUser=False, bcc=None):
    """Send MIME message with content already filled in."""
    if isinstance(frm, tuple):
	frm = formataddr(frm)
    if isinstance(to, list) or isinstance(to, tuple):
        to = ", ".join([isinstance(addr, tuple) and formataddr(addr) or addr for addr in to if addr])
    if isinstance(cc, list) or isinstance(cc, tuple):
        cc = ", ".join([isinstance(addr, tuple) and formataddr(addr) or addr for addr in cc if addr])
    if frm:
	msg['From'] = frm
    msg['To'] = to
    if cc:
	msg['Cc'] = cc
    msg['Subject'] = subject
    msg['X-Test-IDTracker'] = (settings.SERVER_MODE == 'production') and 'no' or 'yes'
    msg['X-IETF-IDTracker'] = ietf.__version__
    if extra:
	for k, v in extra.items():
            if v:
	        msg[k] = v
    if test_mode or settings.SERVER_MODE == 'production':
	send_smtp(msg, bcc)
    elif settings.SERVER_MODE == 'test':
	if toUser:
	    copy_email(msg, to, toUser=True, originalBcc=bcc)
	elif request and request.COOKIES.has_key( 'testmailcc' ):
	    copy_email(msg, request.COOKIES[ 'testmailcc' ],originalBcc=bcc)
    try:
	copy_to = settings.EMAIL_COPY_TO
    except AttributeError:
        copy_to = "*****@*****.**" % settings.SERVER_MODE
    if copy_to and not test_mode: # if we're running automated tests, this copy is just annoying
        if bcc:
            msg['X-Tracker-Bcc']=bcc
        copy_email(msg, copy_to,originalBcc=bcc)
Пример #16
0
def send_email(sender, recipient, subject, body):
    header_charset = 'ISO-8859-1'
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    smtp = SMTP("localhost")
    smtp.sendmail(sender, recipient, msg.as_string())
    smtp.quit()
Пример #17
0
def sendStatusMail(context):
    """Sends notification on the order status to the orderer and faborders.salesEmail
    """
    mail_text = u""
    charset = 'utf-8'

    portal = getSite()
    mail_template = portal.mail_order_status_change
    faborders = context.aq_parent

    from_address = faborders.salesEmail
    from_name = "Fritzing Fab"
    to_address = context.email
    user = context.getOwner()
    to_name = user.getProperty('fullname')
    # we expect a name to contain non-whitespace characters:
    if not re.search('\S', to_name):
        to_name = u"%s" % user

    state_id = getStateId(False, context)
    state_title = getStateTitle(False, context)
    delivery_date = faborders.nextProductionDelivery

    mail_subject = _(u"Your Fritzing Fab order #%s is now %s") % (
        context.id, state_title.lower())

    mail_text = mail_template(
        to_name=to_name,
        to_address=to_address,
        state_id=state_id,
        state_title=state_title,
        delivery_date=delivery_date,
        faborder=context,
        ship_to=IFabOrder['shipTo'].vocabulary.getTerm(context.shipTo).title,
    )

    try:
        host = getToolByName(context, 'MailHost')
        # send our copy:
        host.send(
            MIMEText(mail_text, 'plain', charset),
            mto=formataddr((from_name, from_address)),
            mfrom=formataddr((from_name, from_address)),
            subject=mail_subject,
            charset=charset,
            msg_type="text/plain",
        )
        # send notification for the orderer:
        host.send(
            MIMEText(mail_text, 'plain', charset),
            mto=formataddr((to_name, to_address)),
            mfrom=formataddr((from_name, from_address)),
            subject=mail_subject,
            charset=charset,
            msg_type="text/plain",
        )
    except SMTPRecipientsRefused:
        # Don't disclose email address on failure
        raise SMTPRecipientsRefused('Recipient address rejected by server')
Пример #18
0
def sendStatusMail(context):
    """Sends notification on the order status to the orderer and faborders.salesEmail
    """
    mail_text = u""
    charset = 'utf-8'
    
    portal = getSite()
    mail_template = portal.mail_order_status_change
    faborders = context.aq_parent
    
    from_address = faborders.salesEmail
    from_name = "Fritzing Fab"
    to_address = context.email
    user  = context.getOwner()
    to_name = user.getProperty('fullname')
    # we expect a name to contain non-whitespace characters:
    if not re.search('\S', to_name):
        to_name = u"%s" % user
    
    state_id = getStateId(False, context)
    state_title = getStateTitle(False, context)
    delivery_date = faborders.nextProductionDelivery
    
    mail_subject = _(u"Your Fritzing Fab order #%s is now %s") % (context.id, state_title.lower())
    
    mail_text = mail_template(
        to_name = to_name,
        to_address = to_address,
        state_id = state_id,
        state_title = state_title,
        delivery_date = delivery_date,
        faborder = context,
        ship_to = IFabOrder['shipTo'].vocabulary.getTerm(context.shipTo).title,
        )
    
    try:
        host = getToolByName(context, 'MailHost')
        # send our copy:
        host.send(
            MIMEText(mail_text, 'plain', charset), 
            mto = formataddr((from_name, from_address)),
            mfrom = formataddr((from_name, from_address)),
            subject = mail_subject,
            charset = charset,
            msg_type="text/plain",
        )
        # send notification for the orderer:
        host.send(
            MIMEText(mail_text, 'plain', charset), 
            mto = formataddr((to_name, to_address)),
            mfrom = formataddr((from_name, from_address)),
            subject = mail_subject,
            charset = charset,
            msg_type="text/plain",
        )
    except SMTPRecipientsRefused:
        # Don't disclose email address on failure
        raise SMTPRecipientsRefused('Recipient address rejected by server')
Пример #19
0
    def update(self):
        super(EventNotification, self).update()

        context = removeAllProxies(self.context)
        request = self.request
        principal = self.request.principal
        ids = getUtility(IIntIds)

        self.name = context.__name__

        mailer = getUtility(IMailer)

        profile = IPersonalProfile(principal, None)
        if profile is not None and profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u'To', formataddr((author, profile.email),))
        else:
            self.author = principal.title or principal.id

        self.addHeader(u'From', formataddr((self.author, mailer.email_from_address),))

        self.addHeader(u'In-Reply-To', u'<*****@*****.**>'%ids.getId(context))

        self.url = u'%s/'%absoluteURL(context, request)
        self.title = u'%s'%context.title
        self.calendar = context.__parent__

        # calendar
        self.calendarUrl = u'%s/'%absoluteURL(self.calendar, request)

        # owner
        self.owner = IOwnership(context).owner

        members = []
        for member in context.attendees:
            principal = getPrincipal(member)
            oneMember = {}

            homeFolder = IPersonalSpace(principal, None)
            profileUrl = homeFolder is not None \
                and '%s/profile/'%absoluteURL(homeFolder, request) or ''

            oneMember["url"] = profileUrl
            oneMember["title"] = principal.title
            members.append(oneMember)

        info = {
            'event': context,
            'sdDate': context.startDate.strftime('%m/%d/%Y'),
            'sdTime': context.startDate.strftime('%H:%M'),
            'edDate': context.endDate.strftime('%m/%d/%Y'),
            'edTime': context.endDate.strftime('%H:%M'),
            'members': members}

        self.info = info
Пример #20
0
    def send_email(self, recipients, subject, body, attachments=None):
        """Prepare and send email to the recipients

        :param recipients: a list of email or name,email strings
        :param subject: the email subject
        :param body: the email body
        :param attachments: list of email attachments
        :returns: True if all emails were sent, else false
        """

        recipient_pairs = map(self.parse_email, recipients)
        template_context = {
            "recipients":
            "\n".join(map(lambda p: formataddr(p), recipient_pairs))
        }

        body_template = Template(
            safe_unicode(body)).safe_substitute(**template_context)

        _preamble = "This is a multi-part message in MIME format.\n"
        _from = formataddr((self.email_from_name, self.email_from_address))
        _subject = Header(s=safe_unicode(subject), charset="utf8")
        _body = MIMEText(body_template, _subtype="plain", _charset="utf8")

        # Create the enclosing message
        mime_msg = MIMEMultipart()
        mime_msg.preamble = _preamble
        mime_msg["Subject"] = _subject
        mime_msg["From"] = _from
        mime_msg.attach(_body)

        # Attach attachments
        for attachment in attachments:
            mime_msg.attach(attachment)

        success = []
        # Send one email per recipient
        for pair in recipient_pairs:
            # N.B.: Headers are added additive, so we need to remove any
            #       existing "To" headers
            # No KeyError is raised if the key does not exist.
            # https://docs.python.org/2/library/email.message.html#email.message.Message.__delitem__
            del mime_msg["To"]

            # N.B. we use just the email here to prevent this Postfix Error:
            # Recipient address rejected: User unknown in local recipient table
            mime_msg["To"] = pair[1]
            msg_string = mime_msg.as_string()
            sent = self.send(msg_string)
            if not sent:
                logger.error("Could not send email to {}".format(pair))
            success.append(sent)

        if not all(success):
            return False
        return True
Пример #21
0
def send_email(recipient, subject, body, sender=u'Компьютерный магазин <*****@*****.**>'):
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    localhost port 25.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
	try:
	    body.encode(body_charset)
	except UnicodeError:
	    pass
	else:
	    break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    #msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg = MIMEMultipart('alternative')
    part = MIMEText(body.encode(body_charset), 'html', body_charset)
    msg.attach(part)

    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), body_charset)

    msg = StringIO(str(msg))
    d = defer.Deferred()
    factory = ESMTPSenderFactory(sender_addr, mailpassword, sender_addr, recipient, msg, d, requireTransportSecurity=False)
    reactor.connectTCP('smtp.yandex.ru', 587, factory)
    return d
Пример #22
0
def send_email(sender, recipient, subject, body, content_type='plain'):
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    localhost port 25.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), content_type, body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    try:
        # Send the message via SMTP to localhost:25
        smtp = SMTP("127.0.0.1")
        smtp.ehlo()
        smtp.sendmail(sender_addr, recipient, msg.as_string())
        smtp.quit()
    except Exception as ex:
        pass
Пример #23
0
def send_email(sender, recipient, subject, body, content_type="plain"):
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    localhost port 25.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = "ISO-8859-1"

    # We must choose the body charset manually
    for body_charset in "US-ASCII", "ISO-8859-1", "UTF-8":
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode("ascii")
    recipient_addr = recipient_addr.encode("ascii")

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), content_type, body_charset)
    msg["From"] = formataddr((sender_name, sender_addr))
    msg["To"] = formataddr((recipient_name, recipient_addr))
    msg["Subject"] = Header(unicode(subject), header_charset)

    try:
        # Send the message via SMTP to localhost:25
        smtp = SMTP("127.0.0.1")
        smtp.ehlo()
        smtp.sendmail(sender_addr, recipient, msg.as_string())
        smtp.quit()
    except Exception as ex:
        pass
Пример #24
0
	def send_support_mail(self, reporting_user, problem, description, reason, user_email):
		"""
		Sends an email to us, the zoto admins from the web-based support page.

		@param reporting_user: username of reporting user
		@type reporting_user: String

		@param problem: subject line of mail form
		@type problem: String

		@param description: body of mail form
		@type description: String
		
		@param reason: one of 4 radio buttons on form - love_us, bugs, support, feature
		@type reason: String
		
		@param user_email: email of reporting user
		@type user_email: String

		@return: nothing
		@rtype: nothing
		"""
		body = u"""
Username: %s
Email Address: %s

Reason: %s
Subject: %s

%s
   		""" % (reporting_user, user_email, reason, problem, description)

		msg = u'Mime-version: 1.0\n'
		msg += u'Date: %s\n' % formatdate(localtime=True)
		msg += u'To: %s\n' % formataddr((u'Zoto Website Support', u'*****@*****.**'))
		msg += u'From: %s\n' % formataddr((u'Website Support', '*****@*****.**'))
		msg += u'Reply-To: %s\n' % formataddr((reporting_user, user_email))
		msg += u'Subject: SUPPORT MESSAGE FROM %s\n' % reporting_user
		msg += u'X-Mailer: Zoto AZTK\n'
		msg += u'Content-Type: text/plain; charset="utf-8"\n'
		msg += u'Content-Transfer-Encoding: 7bit\n'
		msg += u'\n'
		msg += body
			
		# strap a nice date format on the outgoing filename (it used to a timestamp)
		d = datetime(1,1,1)
		now = d.now().strftime("%d%b%y-%I%M%S%p")
		rand = random.randrange(1000, 9999)
		f = codecs.open(os.path.join(self.OUTBOX_DIR, "ADMIN_SUPPORT_MSG_%s_%s.msg" % (now, rand)), 'w', 'latin-1')
		f.write(msg)
		f.close()
		
		os.system('/usr/bin/python %s/bin/delivermail.py >> %s/delivermail.run.out 2>&1 &' % (aztk_config.aztk_root, aztk_config.setup.get('paths', 'logs')))
Пример #25
0
    def update(self):
        super(InvitationMail, self).update()

        context = self.context

        self.url = u"%s/join.html?invitationCode=%s" % (absoluteURL(getSite(), self.request), context.id)

        profile = IPersonalProfile(self.request.principal, None)
        if profile is not None and profile.email:
            self.addHeader(u"From", formataddr((profile.title, profile.email)))

        self.addHeader(u"To", formataddr((context.name, context.principal)))
Пример #26
0
def Send(smtp, fromEmail, toEmail, subject, body):
	body_charset = header_charset = "UTF-8"
	msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
	msg['From'] = formataddr((fromEmail, fromEmail))
	msg['To'] = formataddr((toEmail, toEmail))
	msg['Subject'] = Header(unicode(subject), header_charset)

	try:
		res = smtp.sendmail(fromEmail, toEmail, msg.as_string())
	except smtplib.SMTPException, e:
		print("Failed to send alert email!")
		print(str(e))
		pass
Пример #27
0
    def __call__(self):
        if 'submitted' in self.request:
            self.items = self.context.objectValues()
            self.pricelist_content = self.lineitems_pt()

            portal = context.portal_url.getPortalObject()
            lab = context.bika_labinfo.laboratory
            request = context.REQUEST

            ar_query_results = portal.portal_mailtemplates.getTemplate(
                'bika', request.mail_template)

            headers = {}
            headers['Date'] = DateTime().rfc822()
            from_addr = headers['From'] = formataddr(
                (encode_header(lab.Title()), lab.getEmailAddress())
            )

            if 'Contact_email_address' in request:
                contact_address = request.Contact_email_address
                msg = 'portal_status_message=Pricelist sent to %s' % (
                    contact_address)
            else:
                contact = context.reference_catalog.lookupObject(request.Contact_uid)
                contact_address = formataddr(
                    (encode_header(contact.getFullname()),
                      contact.getEmailAddress())
                )
                msg = 'portal_status_message=Pricelist sent to %s at %s' % (
                    contact.Title(), contact.getEmailAddress())

            to_addrs = []
            to_addr = headers['To'] = contact_address
            to_addrs.append(to_addr)
            # send copy to lab
            to_addrs.append(from_addr)

            to_addrs = tuple(to_addrs)
            info = {'request': request,
                    'pricelist': context,
                    'portal': portal}

            message = pmt.createMessage(
                'bika', request.mail_template, info, headers, text_format='html')
            sendmail(portal, from_addr, to_addrs, message)

            request.RESPONSE.redirect('%s?%s' % (context.absolute_url(), msg))

            return self.template()
        else:
            return self.form_template()
Пример #28
0
    def __call__(self):
        if 'submitted' in self.request:
            self.items = self.context.objectValues()
            self.pricelist_content = self.lineitems_pt()

            portal = context.portal_url.getPortalObject()
            lab = context.bika_labinfo.laboratory
            request = context.REQUEST

            ar_query_results = portal.portal_mailtemplates.getTemplate(
                'bika', request.mail_template)

            headers = {}
            headers['Date'] = DateTime().rfc822()
            from_addr = headers['From'] = formataddr(
                (encode_header(lab.Title()), lab.getEmailAddress()))

            if 'Contact_email_address' in request:
                contact_address = request.Contact_email_address
                msg = 'portal_status_message=Pricelist sent to %s' % (
                    contact_address)
            else:
                contact = context.reference_catalog.lookupObject(
                    request.Contact_uid)
                contact_address = formataddr(
                    (encode_header(contact.getFullname()),
                     contact.getEmailAddress()))
                msg = 'portal_status_message=Pricelist sent to %s at %s' % (
                    contact.Title(), contact.getEmailAddress())

            to_addrs = []
            to_addr = headers['To'] = contact_address
            to_addrs.append(to_addr)
            # send copy to lab
            to_addrs.append(from_addr)

            to_addrs = tuple(to_addrs)
            info = {'request': request, 'pricelist': context, 'portal': portal}

            message = pmt.createMessage('bika',
                                        request.mail_template,
                                        info,
                                        headers,
                                        text_format='html')
            sendmail(portal, from_addr, to_addrs, message)

            request.RESPONSE.redirect('%s?%s' % (context.absolute_url(), msg))

            return self.template()
        else:
            return self.form_template()
Пример #29
0
    def update(self):
        super(NotificationMail, self).update()

        topic = self.context
        self.topic = topic
        message = self.contexts[0]
        forum = topic.__parent__
        request = self.request
        self.url = '%s/'%absoluteURL(message, request)
        self.message = message
        self.forum = forum
        self.forumurl = absoluteURL(forum, request)
        self.topicurl = absoluteURL(topic, request)

        principal = IOwnership(message).owner

        profile = IPersonalProfile(principal)
        if profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u'From', formataddr((author, profile.email),))
        else:
            self.author = principal.title or principal.id

        self.site = getSite()

        destination = IMailInDestination(forum)
        if destination.enabled:
            self.addHeader(u'To', destination.address)
            self.addHeader(u'Reply-To', destination.address)
            self.addHeader(u'List-Post', u'<mailto:%s>'%destination.address)
        else:
            self.addHeader(u'To', formataddr((self.author, profile.email),))

        ids = getUtility(IIntIds)
        msgId = ids.getId(message)
        topicId = ids.getId(topic)

        if message.__name__ == TOPIC_FIRST_MESSAGE:
            self.messageId = u'<*****@*****.**>'%(topicId)
        else:
            self.messageId = u'<*****@*****.**>'%(topicId, msgId)

        self.addHeader(u'List-Id', u'%s'%forum.title)
        self.addHeader(u'List-Unsubscribe', u'%s/@@notifications'%self.forumurl)
        self.addHeader(u'List-Subscribe', u'%s/@@notifications'%self.forumurl)
        self.addHeader(u'List-Archive', u'%s/'%self.forumurl)

        self.addHeader(u'In-Reply-To', u'<*****@*****.**>'%topicId)
        self.addHeader(u'References', u'<*****@*****.**>'%topicId)
def get_maildata(sender, recipient, subject, body):
    # for python<2.7
    # source: http://mg.pov.lt/blog/unicode-emails-in-python
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)
    sender_name = str(Header(unicode(sender_name), 'utf8'))
    recipient_name = str(Header(unicode(recipient_name), 'utf8'))
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')
    msg = MIMEText(body.encode('utf8'), 'html', 'utf8')
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), 'utf8')
    return msg.as_string()
Пример #31
0
def send_mail_mime(request,
                   to,
                   frm,
                   subject,
                   msg,
                   cc=None,
                   extra=None,
                   toUser=False,
                   bcc=None):
    """Send MIME message with content already filled in."""
    if isinstance(frm, tuple):
        frm = formataddr(frm)
    if isinstance(to, list) or isinstance(to, tuple):
        to = ", ".join([
            isinstance(addr, tuple) and formataddr(addr) or addr for addr in to
            if addr
        ])
    if isinstance(cc, list) or isinstance(cc, tuple):
        cc = ", ".join([
            isinstance(addr, tuple) and formataddr(addr) or addr for addr in cc
            if addr
        ])
    if frm:
        msg['From'] = frm
    msg['To'] = to
    if cc:
        msg['Cc'] = cc
    msg['Subject'] = subject
    msg['X-Test-IDTracker'] = (settings.SERVER_MODE
                               == 'production') and 'no' or 'yes'
    msg['X-IETF-IDTracker'] = ietf.__version__
    if extra:
        for k, v in extra.items():
            if v:
                msg[k] = v
    if test_mode or settings.SERVER_MODE == 'production':
        send_smtp(msg, bcc)
    elif settings.SERVER_MODE == 'test':
        if toUser:
            copy_email(msg, to, toUser=True, originalBcc=bcc)
        elif request and request.COOKIES.has_key('testmailcc'):
            copy_email(msg, request.COOKIES['testmailcc'], originalBcc=bcc)
    try:
        copy_to = settings.EMAIL_COPY_TO
    except AttributeError:
        copy_to = "*****@*****.**" % settings.SERVER_MODE
    if copy_to and not test_mode:  # if we're running automated tests, this copy is just annoying
        if bcc:
            msg['X-Tracker-Bcc'] = bcc
        copy_email(msg, copy_to, originalBcc=bcc)
Пример #32
0
    def sendmail(self, toaddr, subject, body, cc=[], bcc=[]):

        if not self.server:
            self.connect()

        logging.info('Send mail to %s' % toaddr)

        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        from_name, from_addr = parseaddr(self.fromaddr)
        to_name, to_addr = parseaddr(toaddr)

        from_name = str(Header(unicode(from_name), self.header_charset))
        to_name = str(Header(unicode(to_name), self.header_charset))

        from_addr = from_addr.encode('ascii')
        to_addr = to_addr.encode('ascii')

        if from_addr == to_addr:
            logging.info('Send mail to myself is not allowed now.')
            return

        email_format = 'html' if self.HTML else 'plain'

        msg = MIMEText(body.encode(body_charset), email_format, body_charset)
        msg['From'] = formataddr((from_name, from_addr))
        msg['To'] = formataddr((to_name, to_addr))

        if cc:
            msg['CC'] = ', '.join([self._formataddr(x) for x in cc])

        if bcc:
            msg['BCC'] = ', '.join([self._formataddr(x) for x in bcc])

        msg['Subject'] = Header(unicode(subject), self.header_charset)
        msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

        try:
            self.server.sendmail(self.fromaddr, [toaddr] + cc + bcc,
                                 msg.as_string())
        except Exception, e:
            logging.error('Send mail from %s:%s to %s failed: %s' %
                          (self.host, self.port, toaddr, e))
Пример #33
0
    def sendmail(self, toaddr, subject, body, cc=[], bcc=[]):

        if not self.server:
            self.connect()

        logging.info( 'Send mail to %s' % toaddr )

        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        from_name, from_addr = parseaddr( self.fromaddr )
        to_name  , to_addr   = parseaddr( toaddr )

        from_name = str(Header(unicode(from_name), self.header_charset))
        to_name = str(Header(unicode(to_name), self.header_charset))

        from_addr = from_addr.encode('ascii')
        to_addr = to_addr.encode('ascii')

        if from_addr == to_addr:
            logging.info( 'Send mail to myself is not allowed now.')
            return

        email_format = 'html' if self.HTML else 'plain'
            
        msg = MIMEText( body.encode(body_charset), email_format, body_charset )
        msg['From'] = formataddr((from_name, from_addr))
        msg['To'] = formataddr((to_name, to_addr))

        if cc:
            msg['CC'] = ', '.join([ self._formataddr(x) for x in cc ])

        if bcc:
            msg['BCC'] = ', '.join([ self._formataddr(x) for x in bcc ])

        msg['Subject'] = Header(unicode(subject), self.header_charset)
        msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

        try:
            self.server.sendmail( self.fromaddr, [toaddr] + cc + bcc, msg.as_string() )
        except Exception, e:
            logging.error( 'Send mail from %s:%s to %s failed: %s' % (
                    self.host, self.port, toaddr, e) )
def secureSend(self, message, mto, mfrom, subject='[No Subject]',
               mcc=None, mbcc=None, subtype='plain', charset='us-ascii',
               debug=False, **kwargs):
    """Deprecated method attempting to maintain backwards
    compatibility for code depending on the SecureMailHost API."""
    # Convert all our address list inputs
    mfrom = email_list_to_string(mfrom, charset)
    mto = email_list_to_string(mto, charset)
    mcc = email_list_to_string(mcc, charset)
    mbcc = email_list_to_string(mbcc, charset)

    # Convert to a message for adding headers.  If it's already a
    # message, copy it to be safe.
    if not isinstance(message, Message):
        if isinstance(message, unicode):
            message.encode(charset)
        message = MIMEText(message, subtype, charset)
    else:
        message = deepcopy(message)

    # Add extra headers
    _addHeaders(message, Subject=Header(subject, charset),
                To=mto, Cc=mcc, From=mfrom,
                **dict((k, Header(v, charset)) for k, v in kwargs.iteritems()))

    all_recipients = [formataddr(pair) for pair in
                      getaddresses((mto, mcc, mbcc))]

    # Convert message back to string for sending
    self._send(mfrom, all_recipients, message.as_string(), immediate=True)
Пример #35
0
 def sendAlertEmail(self):
     # Send an alert email
     laboratory = self.context.bika_setup.laboratory
     subject = self.request.get('subject')
     to = self.request.get('to')
     body = self.request.get('body')
     body = "<br/>".join(body.split("\r\n"))
     mime_msg = MIMEMultipart('related')
     mime_msg['Subject'] = subject
     mime_msg['From'] = formataddr((encode_header(laboratory.getName()),
                                    laboratory.getEmailAddress()))
     mime_msg['To'] = to
     msg_txt = MIMEText(safe_unicode(body).encode('utf-8'), _subtype='html')
     mime_msg.preamble = 'This is a multi-part MIME message.'
     mime_msg.attach(msg_txt)
     succeed = False
     try:
         host = getToolByName(self.context, 'MailHost')
         host.send(mime_msg.as_string(), immediate=True)
     except Exception, msg:
         ar = self.context.id
         logger.error("Panic level email %s: %s" % (ar, str(msg)))
         message = _('Unable to send an email to alert client '
                     'that some results exceeded the panic levels') \
                                          + (": %s" % str(msg))
         self.addMessage(message, 'warning')
Пример #36
0
 def get_article(self):
     article="Newsgroups: "+self.newsgroups+"\n"
     article=article+"From: "+formataddr([self.nick_encoded,self.email])+"\n"
     article=article+"Subject: "+self.subject_encoded+"\n"
     if self.references!="":
         article=article+"References: "+self.references+"\n"
     self.references=""
     article=article+"User-Agent: "+self.user_agent+"\n"
     article=article+"MIME-Version: 1.0\n"
     article=article+"Content-Type: text/plain; charset="+self.output_charset+"\n"
     if self.output_charset.lower()=="us-ascii":
         article=article+"Content-Transfer-Encoding: 7bit\n"
     else:
         article=article+"Content-Transfer-Encoding: 8bit\n"
     if self.generate_mid=="True":
         mid=make_msgid("XPN")
         if self.fqdn:
             left,right=mid.split("@")
             def clear_fqdn(s,chars):
                 s=s.encode("us-ascii","replace")
                 for char in chars:
                     s=s.replace(char,"")
                 return s
             mid=left+"@"+clear_fqdn(self.fqdn,"@\\\"<>()[];:,")+">"
         article=article+"Message-ID: "+mid+"\n"
     for header in self.custom_headers:
         article=article+header+"\n"
     article=article+"\n"
     article=article.encode("utf-8")+self.body_encoded
     return article
Пример #37
0
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_unicode(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val = val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ('to', 'from', 'cc'):
            result = []
            for nm, addr in getaddresses((val,)):
                nm = str(Header(nm.encode(encoding), encoding))
                try:
                    addr = addr.encode('ascii')
                except UnicodeEncodeError:  # IDN
                    addr = str(Header(addr.encode(encoding), encoding))
                result.append(formataddr((nm, addr)))
            val = ', '.join(result)
        else:
            val = Header(val.encode(encoding), encoding)
    else:
        if name.lower() == 'subject':
            val = Header(val)
    return name, val
Пример #38
0
    def __subscribe(self,
                    email,
                    first_name=u'',
                    last_name=u'',
                    send_welcome_msg=False):
        from email.Utils import formataddr

        if settings.DEBUG:
            return

        url = '%s/admin/%s/members/add' % (settings.MAILMAN_URL, self.name)

        first_name = check_encoding(first_name, settings.MAILMAN_ENCODING)
        last_name = check_encoding(last_name, settings.MAILMAN_ENCODING)
        email = check_encoding(email, settings.MAILMAN_ENCODING)
        name = '%s %s' % (first_name, last_name)

        SUBSCRIBE_DATA['adminpw'] = settings.MAILMAN_PASSWORD
        SUBSCRIBE_DATA[
            'send_welcome_msg_to_this_batch'] = send_welcome_msg and "1" or "0"
        SUBSCRIBE_DATA['subscribees_upload'] = formataddr(
            [name.strip(), email])
        opener = urllib2.build_opener(
            MultipartPostHandler(settings.MAILMAN_ENCODING, True))
        content = opener.open(url, SUBSCRIBE_DATA).read()

        (msg, member) = self.__parse_status_content(
            unicode(content, settings.MAILMAN_ENCODING))
        if (msg not in SUBSCRIBE_MSG):
            error = u'%s: %s' % (
                unicode(msg, encoding=settings.MAILMAN_ENCODING),
                unicode(member, encoding=settings.MAILMAN_ENCODING))
            raise Exception(error.encode(settings.MAILMAN_ENCODING))
Пример #39
0
def secureSend(self, message, mto, mfrom, subject='[No Subject]',
               mcc=None, mbcc=None, subtype='plain', charset='us-ascii',
               debug=False, **kwargs):
    """Deprecated method attempting to maintain backwards
    compatibility for code depending on the SecureMailHost API."""
    # Convert all our address list inputs
    mfrom = email_list_to_string(mfrom, charset)
    mto = email_list_to_string(mto, charset)
    mcc = email_list_to_string(mcc, charset)
    mbcc = email_list_to_string(mbcc, charset)

    # Convert to a message for adding headers.  If it's already a
    # message, copy it to be safe.
    if not isinstance(message, Message):
        if isinstance(message, unicode):
            message.encode(charset)
        message = MIMEText(message, subtype, charset)
    else:
        message = deepcopy(message)

    # Add extra headers
    _addHeaders(message, Subject=Header(subject, charset),
                To=mto, Cc=mcc, From=mfrom,
                **dict((k, Header(v, charset)) for k, v in kwargs.iteritems()))

    all_recipients = [formataddr(pair) for pair in
                      getaddresses((mto, mcc, mbcc))]

    # Convert message back to string for sending
    self._send(mfrom, all_recipients, message.as_string(), immediate=True)
Пример #40
0
def sendEmail( fromEmail, toList, smtpServerHost, subject, reportText, \
        reportHtml, log ):
    """
    This turns the "report" into an email attachment
    and sends it to the EmailTarget(s).
    """
    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = formataddr(fromEmail)
    msg["To"] = _toStr(toList)
    msg1 = MIMEMultipart("alternative")
    msgText1 = MIMEText("<pre>%s</pre>" % reportText, "html")
    msgText2 = MIMEText(reportText)
    msg1.attach(msgText2)
    msg1.attach(msgText1)
    msg.attach(msg1)
    msg = msg.as_string()

    log.debug("Report message:\n\n%s" % msg)
    if len(toList[1]) != 0:
        server = smtplib.SMTP(smtpServerHost)
        server.sendmail(fromEmail[1], toList[1], msg)
        server.quit()
    else:
        # The email list isn't valid, so we write it to stdout and hope
        # it reaches somebody who cares.
        print message
Пример #41
0
def send_attach_file_mail(to_addr_list,
                          subject,
                          message,
                          file_path,
                          from_addr,
                          smtp_host,
                          smtp_port=25,
                          cc_addr_list=[],
                          bcc_addr_list=[]):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = formataddr(('Author', from_addr))
    if len(to_addr_list) != 0:
        msg['To'] = ','.join(to_addr_list)
    if len(cc_addr_list) != 0:
        msg['Cc'] = ','.join(cc_addr_list)
    if len(bcc_addr_list) != 0:
        msg['Bcc'] = ','.join(bcc_addr_list)
    msg['Date'] = formatdate(localtime=True)
    message = MIMEText(message, _charset='utf-8')
    msg.attach(message)
    mime_type, sub_type = mimetypes.guess_type(file_path)
    attachment = MIMEBase(mime_type, sub_type)
    with open(file_path) as attach_file_obj:
        attachment.set_payload(attach_file_obj.read())
    Encoders.encode_base64(attachment)
    msg.attach(attachment)
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=os.path.basename(file_path))
    s = smtplib.SMTP(smtp_host, smtp_port)
    s.sendmail(from_addr, to_addr_list + cc_addr_list + bcc_addr_list,
               msg.as_string())
    s.quit()
Пример #42
0
    def update(self):
        super(StatusNotificationMail, self).update()

        event = self.context
        request = self.request

        draft = event.draft
        self.draft = event.draft

        self.url = "%s/" % absoluteURL(draft, request)

        principal = IOwnership(draft).owner

        profile = IPersonalProfile(principal)
        if profile.email:
            author = profile.title
            self.author = author
            self.addHeader(u"To", formataddr((self.author, profile.email)))
        else:
            self.author = principal.title or principal.id

        cId = getUtility(IIntIds).getId(draft)

        self.site = getSite()
        self.messageId = u"<*****@*****.**>" % (cId, time.time())
        self.title = draft.content.title
        self.comment = event.comment
Пример #43
0
def format_address(name, address):
    r"""Formats a name and address to be used as an email header.

        >>> format_address('Name', '*****@*****.**')
        'Name <*****@*****.**>'
        >>> format_address('', '*****@*****.**')
        '*****@*****.**'
        >>> format_address(None, u'*****@*****.**')
        '*****@*****.**'

    It handles unicode and characters that need quoting as well.

        >>> format_address(u'F\xf4\xf4 Bar', '*****@*****.**')
        '=?utf-8?b?RsO0w7QgQmFy?= <*****@*****.**>'

        >>> format_address('Foo [Baz] Bar', '*****@*****.**')
        '"Foo \\[Baz\\] Bar" <*****@*****.**>'

    Really long names doesn't get folded, since we're not constructing
    an e-mail header here.

        >>> formatted_address = format_address(
        ...     'a '*100, '*****@*****.**')
        >>> '\n' in formatted_address
        False
    """
    if not name:
        return str(address)
    name = str(Header(name))
    # Using Header to encode the name has the side-effect that long
    # names are folded, so let's unfold it again.
    name = ''.join(name.splitlines())
    return str(formataddr((name, address)))
Пример #44
0
def sendmail(to, subject, body, sender=None, html=None, sender_name=None):
    sender_name = sender_name or SMTP.SENDER_NAME
    sender = sender or SMTP.SENDER
    # print to, '#!!!!!!!!!!!!!!!!!!'
    if html:
        text_subtype = 'html'
        msg = MIMEText(html, text_subtype, 'utf-8')
    else:
        text_subtype = 'plain'
        msg = MIMEText(body, text_subtype, 'utf-8')

    # print SMTP

    msg['Subject'] = Header(subject, 'utf-8')
    if sender_name is None:
        sender_name = sender.split('@', 1)[0]
    sender_name = str(Header(sender_name, 'utf-8'))
    msg['From'] = formataddr((sender_name, sender))
    msg['To'] = to
    #msg['Bcc'] = MAIL_ARCHIVE
    smtp = smtplib.SMTP(SMTP.HOST)
    #smtp.set_debuglevel(True)
    print SMTP
    smtp.login(SMTP.USERNAME, SMTP.PASSWORD)
    smtp.sendmail(sender, to, msg.as_string())
Пример #45
0
def sendmail(to, subject, body, sender=None, html=None, sender_name=None):
    sender_name = sender_name or SMTP.SENDER_NAME
    sender = sender or SMTP.SENDER
    # print to, '#!!!!!!!!!!!!!!!!!!'
    if html:
        text_subtype = 'html'
        msg = MIMEText(html, text_subtype, 'utf-8')
    else:
        text_subtype = 'plain'
        msg = MIMEText(body, text_subtype, 'utf-8')

    # print SMTP

    msg['Subject'] = Header(subject, 'utf-8')
    if sender_name is None:
        sender_name = sender.split('@', 1)[0]
    sender_name = str(Header(sender_name, 'utf-8'))
    msg['From'] = formataddr((sender_name, sender))
    msg['To'] = to
    #msg['Bcc'] = MAIL_ARCHIVE
    smtp = smtplib.SMTP(SMTP.HOST)
    #smtp.set_debuglevel(True)
    print SMTP
    smtp.login(SMTP.USERNAME, SMTP.PASSWORD)
    smtp.sendmail(sender, to, msg.as_string())
Пример #46
0
    def send_mails(self):
        srvr = self.db.config.MAIL_HOST
        if opt.send_via:
            srvr = opt.send_via
        date = "Date: %s" % formatdate(time(), True)
        smtp = SMTP(srvr)
        subj = "Subject: Status of IT-issues"
        mime = '\n'.join \
            (( 'Mime-Version: 1.0'
             , 'Content-Type: text/plain; charset=UTF-8'
             , 'Content-Transfer-Encoding: 8bit'
            ))

        frm = opt.mailfrom or self.db.config.ADMIN_EMAIL
        if '@' not in frm:
            frm = '@'.join((frm, self.db.config.MAIL_DOMAIN))
        hfrm = "From: %s" % formataddr(('Do not reply', frm))

        for uid, m in sorted(self.messages.iteritems()):
            assert (uid)
            user = self.db.user.getnode(uid)
            addr = user.address
            to = "To: %s" % addr
            try:
                mail = '\n'.join \
                    ((subj, to, hfrm, date, "X-" + date, mime, '\n', m))
                smtp.sendmail(frm, addr, mail)
            except SMTPRecipientsRefused, cause:
                print(cause, file=sys.stderr)
Пример #47
0
def send_panic_email(view):
    ar = view.context
    if not IAnalysisRequest.providedBy(ar):
        return False

    if not ar.has_analyses_in_panic():
        addMessage(view, _("No results exceed the panic levels"), 'warning')
        return False

    # Send an alert email
    laboratory = view.context.bika_setup.laboratory
    subject = view.request.get('subject')
    to = view.request.get('to')
    body = view.request.get('email_body')
    body = "<br/>".join(body.split("\r\n"))
    mime_msg = MIMEMultipart('related')
    mime_msg['Subject'] = subject
    mime_msg['From'] = formataddr(
        (encode_header(laboratory.getName()),
         laboratory.getEmailAddress()))
    mime_msg['To'] = to
    msg_txt = MIMEText(safe_unicode(body).encode('utf-8'), _subtype='html')
    mime_msg.preamble = 'This is a multi-part MIME message.'
    mime_msg.attach(msg_txt)
    try:
        host = getToolByName(view.context, 'MailHost')
        host.send(mime_msg.as_string(), immediate=True)
    except Exception, msg:
        ar = view.context.id
        logger.error("Panic level email %s: %s" % (ar, str(msg)))
        message = _('Unable to send an email to alert client '
                    'that some results exceeded the panic levels') \
                  + (": %s" % str(msg))
        addMessage(view, message, 'warning')
        return False
Пример #48
0
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_unicode(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError(
            "Header values can't contain newlines (got %r for header %r)" %
            (val, name))
    try:
        val = val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ('to', 'from', 'cc'):
            result = []
            for nm, addr in getaddresses((val, )):
                nm = str(Header(nm.encode(encoding), encoding))
                try:
                    addr = addr.encode('ascii')
                except UnicodeEncodeError:  # IDN
                    addr = str(Header(addr.encode(encoding), encoding))
                result.append(formataddr((nm, addr)))
            val = ', '.join(result)
        else:
            val = Header(val.encode(encoding), encoding)
    else:
        if name.lower() == 'subject':
            val = Header(val)
    return name, val
Пример #49
0
def _toStr(toList):
    """Formats outgoing address list
    Args:
    toList(list of str) - email addresses
    """

    names = [formataddr(i) for i in zip(*toList)]
    return ', '.join(names)
Пример #50
0
 def get_article(self):
     article="To: "+formataddr([self.to_nick_encoded,self.to_email])+"\n"
     article=article+"From: "+formataddr([self.nick_encoded,self.email])+"\n"
     article=article+"Subject: "+self.subject_encoded+"\n"
     article=article+"Date: "+self.date+"\n"
     if self.references!="":
         article=article+"References: "+self.references+"\n"
     self.references=""
     article=article+"User-Agent: "+self.user_agent+"\n"
     article=article+"MIME-Version: 1.0\n"
     article=article+"Content-Type: text/plain; charset="+self.output_charset+"\n"
     if self.output_charset.lower()=="us-ascii":
         article=article+"Content-Transfer-Encoding: 7bit\n"
     else:
         article=article+"Content-Transfer-Encoding: 8bit\n"
     article=article+"\n"
     article=article.encode("utf-8")+self.body_encoded
     return article
Пример #51
0
def send_message(user_id, user_name, user_info, subject, body, attachments=[]):
    email = user_id
    name = user_name or user_info.get('name', email)
    recipient = formataddr((name, email))
    message = EmailMessage(subject, body, settings.SERVER_EMAIL, [recipient])
    for attachment in attachments:
        message.attach(*attachment)

    message.send(fail_silently=False)
Пример #52
0
    def _send_owner_mail(self, order):
        """Send order notification to shop owner.
        """
        show_prices = self.show_prices(order)
        mail_to = formataddr(("Shop Owner", self.shop_config.shop_email))
        customer_name = "%s %s" % (order.customer_firstname,
                                   order.customer_lastname)
        customer_address = formataddr((customer_name, order.customer_email))
        mail_subject = '[%s] Order %s by %s' % (self.shop_config.shop_name,
                                               order.order_id,
                                               customer_name)

        mail_view = getMultiAdapter((self.context, self.context.REQUEST),
                                    name=u'shopowner_mail_view')
        msg_body = mail_view(order=order,
                             show_prices=show_prices,
                             shop_config=self.shop_config)
        self._send_mail(mail_to, mail_subject, msg_body, reply_to=customer_address)
Пример #53
0
def to_str(cp):
    toNames = cp.get("email", "toNames")
    toStr = cp.get("email", "toStr")
    toNames = eval(toNames, {}, {})
    toStr = eval(toStr, {}, {})
    if len(toNames) > 1 and cp.getboolean("info", "dev"):
        raise Exception("Cannot send to multiple recipients in dev mode.")
    names = [formataddr(i) for i in zip(toNames, toStr)]
    return ', '.join(names)
Пример #54
0
def send_email(sender, recipient, subject, body):
    if DEBUG:
        subject = 'DEBUG: to(%s), %s' % (recipient, subject)
        recipient = DEBUG
    from smtplib import SMTP
    from email.MIMEText import MIMEText
    from email.Header import Header
    from email.Utils import parseaddr, formataddr
    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'
    # We must choose the body charset manually
    for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break
    else:
        msg = 'cannot send email, no charset found'
        my_logger.error(msg)
        body = u'cannot send email, no charset found'
        print 'body charset', body_charset
    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)
    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))
    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')
    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)
    # Send the message via SMTP to localhost:25
    smtp = SMTP("localhost")
    smtp.sendmail(sender, recipient, msg.as_string())
    smtp.quit()
Пример #55
0
    def _send_supplier_mail(self, supplier, order):
        """Send order notification to a (single) supplier.
        """
        show_prices = self.show_prices(order)
        mail_to = formataddr(supplier)
        customer_name = "%s %s" % (order.customer_firstname,
                                   order.customer_lastname)
        customer_address = formataddr((customer_name, order.customer_email))
        mail_subject = '[%s] Order %s by %s' % (self.shop_config.shop_name,
                                               order.order_id,
                                               customer_name)

        mail_view = getMultiAdapter((self.context, self.context.REQUEST),
                                    name=u'supplier_mail_view')
        msg_body = mail_view(order=order,
                             show_prices=show_prices,
                             has_order_dimensions=self.has_order_dimensions(order),
                             shop_config=self.shop_config,
                             supplier=supplier)
        self._send_mail(mail_to, mail_subject, msg_body, reply_to=customer_address)
def email_address_for_member(member):
    """Return a formatted fullname plus email address for this member.

    We create a fake Member class for testing:

    >>> class Member(object):
    ...     def __init__(self, fullname='', email=''):
    ...         self.fullname = fullname
    ...         self.email = email
    ...     def getProperty(self, propname, default=None):
    ...         if propname == 'fullname':
    ...             return self.fullname
    ...         if propname == 'email':
    ...             return self.email
    ...         return default

    We define an alias for this function to make the line shorter:

    >>> efm = email_address_for_member

    Now we do some tests:

    >>> efm(None)
    ''
    >>> efm(Member())
    ''
    >>> efm(Member(fullname='Maurits van Rees'))
    ''
    >>> efm(Member(email='[email protected]'))
    '[email protected]'
    >>> efm(Member('Maurits van Rees', '[email protected]'))
    'Maurits van Rees <[email protected]>'

    The parseaddr function can get confused in the face of special
    characters, which leads to misinterpreting the email address.  I
    saw that in the browser, but could not find a way to create a test
    for that.  Anyway, in case of confusion we just return the email
    address and not the fullname.

    """
    if not member:
        # Maybe a test user?
        return ''

    email = member.getProperty('email', '')
    if not email:
        return ''
    fullname = member.getProperty('fullname', '')

    formatted = formataddr((fullname, email))
    if parseaddr(formatted)[1] != email:
        # formataddr probably got confused by special characters.
        return email
    return formatted
Пример #57
0
def to_email_address(address, name=""):
    """Convert the given address, name pair to an email address

    :param address: The email address
    :type address: basestring
    :param name: The real name of the person owning the email address
    :type name: basestring
    :returns: Email address suitable for an RFC 2822 From, To or Cc header
    """
    pair = (name, address)
    return formataddr(pair)
Пример #58
0
def encode_emailaddress(address):
    """
    Encode an email address as ASCII using the Encoded-Word standard.
    Needed to work around http://code.djangoproject.com/ticket/11144
    """
    try:
        return address.encode('ascii')
    except UnicodeEncodeError:
        pass
    nm, addr = parseaddr(address)
    return formataddr((str(Header(nm, settings.DEFAULT_CHARSET)), addr))
Пример #59
0
def send_email(sender, recipient, subject, body):
    SMTPHOST = "HOST"
    SMTPPORT = 25
    SMTPUSER = "******"
    SMTPPASS = "******"

    header_charset = 'UTF-8'

    # We must choose the body charset manually
    for body_charset in 'UTF-8', 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)

    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    smtp = SMTP(SMTPHOST, SMTPPORT)
    smtp.login(SMTPUSER, SMTPPASS)
    smtp.sendmail(sender, recipient, msg.as_string())
    '''