Python email.utils.formataddr() Examples

The following are 30 code examples of email.utils.formataddr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.utils , or try the search function .
Example #1
Source File: wrapper.py    From py-mailinator with MIT License 6 votes vote down vote up
def __init__(self, token, data):
        self.token = token
        self.id = data.get('id', None)
        self.subject = data.get('subject', None)
        self.time = data.get('time', None)
        self.to = data.get('to', None)
        self.seconds_ago = data.get('seconds_ago', None)
        self.ip = data.get('ip')

        try:
            self.origfrom = data['origfrom']
            # Support old Message attributes
            self.fromshort, self.fromfull = parseaddr(self.origfrom)
        except KeyError:
            # Try the old data model
            self.fromfull = data.get('fromfull')
            self.fromshort = data.get('from')
            self.origfrom = formataddr((self.fromshort, self.fromfull))

        self.headers = {}
        self.body = "" 
Example #2
Source File: flask_mail.py    From flask-unchained with MIT License 6 votes vote down vote up
def sanitize_address(addr, encoding='utf-8'):
    if isinstance(addr, str):
        addr = parseaddr(force_text(addr))
    nm, addr = addr

    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            try:
                localpart = Header(localpart, encoding).encode()
            except UnicodeEncodeError:
                localpart = Header(localpart, 'utf-8').encode()
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #3
Source File: message.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, six.string_types):
        addr = parseaddr(force_text(addr))
    nm, addr = addr
    # This try-except clause is needed on Python 3 < 3.2.4
    # http://bugs.python.org/issue14291
    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #4
Source File: drymail.py    From drymail with MIT License 6 votes vote down vote up
def stringify_address(address):
    """
    Converts an address into a string in the `"John Doe" <john@example.com>"` format, which can be directly used in the
    headers of an email.

    Parameters
    ----------
    address : str or (str, str)
        An address. Can be either the email address or a tuple of the name
        and the email address.

    Returns
    -------
    str
        Address as a single string, in the `"John Doe" <john@example.com>"` format. Returns
        `address` unchanged if it's a single string.
    """
    address = ('', address) if isinstance(address, str) else address
    return formataddr((str(Header(address[0], 'utf-8')), address[1])) 
Example #5
Source File: MailService.py    From tieba-zhuaqu with GNU General Public License v3.0 6 votes vote down vote up
def Mail(TO,TITLE,CONTENT):
  ret=True
  my_user = TO
  try:
    msg=MIMEText(CONTENT,'plain','utf-8')
    msg['From']=formataddr(["Kanch's PythonBot @ MyPythonVPS",my_sender])  #括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To']=formataddr(["Autosend by bot",my_user])  #收件人邮箱昵称、收件人邮箱账号
    msg['Subject']=TITLE #邮件的主题
 
    server=smtplib.SMTP("smtp.163.com",25) #发件人邮箱中的SMTP服务器,端口是25
    server.login(my_sender,my_sender_password)  #括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender,my_user,msg.as_string())  #括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit() 
  except Exception:  
    ret=False
  return ret
 
#SendMail("1075900121@qq.com",'主题','括号中对应的是发件人邮箱账号、括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件邮箱密码') 
Example #6
Source File: MailService.py    From tieba-zhuaqu with GNU General Public License v3.0 6 votes vote down vote up
def Mail(TO,TITLE,CONTENT):
  ret=True
  my_user = TO
  try:
    msg=MIMEText(CONTENT,'plain','utf-8')
    msg['From']=formataddr(["Kanch's PythonBot @ MyPythonVPS",my_sender])  #括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To']=formataddr(["Autosend by bot",my_user])  #收件人邮箱昵称、收件人邮箱账号
    msg['Subject']=TITLE #邮件的主题
 
    server=smtplib.SMTP("smtp.163.com",25) #发件人邮箱中的SMTP服务器,端口是25
    server.login(my_sender,my_sender_password)  #括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender,my_user,msg.as_string())  #括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit() 
  except Exception:  
    ret=False
  return ret
 
#SendMail("1075900121@qq.com",'主题','括号中对应的是发件人邮箱账号、括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件邮箱密码') 
Example #7
Source File: MailService.py    From tieba-zhuaqu with GNU General Public License v3.0 6 votes vote down vote up
def Mail(TO,TITLE,CONTENT):
  ret=True
  my_user = TO
  try:
    msg=MIMEText(CONTENT,'plain','utf-8')
    msg['From']=formataddr(["Kanch's PythonBot @ MyPythonVPS",my_sender])  #括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To']=formataddr(["Autosend by bot",my_user])  #收件人邮箱昵称、收件人邮箱账号
    msg['Subject']=TITLE #邮件的主题
 
    server=smtplib.SMTP("smtp.163.com",25) #发件人邮箱中的SMTP服务器,端口是25
    server.login(my_sender,my_sender_password)  #括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender,my_user,msg.as_string())  #括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit() 
  except Exception:  
    ret=False
  return ret
 
#SendMail("1075900121@qq.com",'主题','括号中对应的是发件人邮箱账号、括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件邮箱密码') 
Example #8
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, six.string_types):
        addr = parseaddr(force_text(addr))
    nm, addr = addr
    # This try-except clause is needed on Python 3 < 3.2.4
    # http://bugs.python.org/issue14291
    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #9
Source File: sampleshipment.py    From baobab.lims with GNU General Public License v3.0 6 votes vote down vote up
def workflow_script_ready_to_ship(self):
        #send the email
        lab = self.bika_setup.laboratory
        sender = formataddr((encode_header(lab.getName()), self.getFromEmailAddress()))

        client = self.getClient()
        receiver = formataddr((encode_header(client.getName()), self.getToEmailAddress()))

        samples_text = self.getStringified(self.getSamplesList())

        subject = "Samples ready to ship"
        body = "Automatic email:\n"
        body += 'The samples \"%s\" are ready to ship.' % samples_text

        # print('------------')
        # print(sender)
        # print(receiver)
        # print(body)

        self.send_mail(sender, receiver, subject, body) 
Example #10
Source File: message.py    From lux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, str):
        addr = parseaddr(addr)
    nm, addr = addr
    nm = Header(nm, encoding).encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #11
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def addr_header_encode(text, header_name=None):
    """Encode and line-wrap the value of an email header field containing
    email addresses."""

    # Convert to unicode, if required.
    if not isinstance(text, unicode):
        text = unicode(text, "utf-8")

    text = ", ".join(
        formataddr((header_encode(name), emailaddr))
        for name, emailaddr in getaddresses([text])
    )

    if is_ascii(text):
        charset = "ascii"
    else:
        charset = "utf-8"

    return Header(
        text, header_name=header_name, charset=Charset(charset)
    ).encode() 
Example #12
Source File: shipment.py    From baobab.lims with GNU General Public License v3.0 6 votes vote down vote up
def workflow_script_dispatch_shipment(self):
        """executed after shipment state transition "dispatch"
        """
        # free positions kits occupy
        kits = self.getKits()
        w_tool = getToolByName(self, 'portal_workflow')
        for kit in kits:
            kit.setStorageLocation('')
            w_tool.doActionFor(kit, 'ship')
            kit.reindexObject()

        # Set shipment's date dispatched
        now = DateTime()
        self.setDateDispatched(now)

        to_contact = self.getToContact()
        from_contact = self.getFromContact()
        client = to_contact.aq_parent
        lab = self.bika_setup.laboratory
        subject = "Kits dispatched from {}".format(lab.getName())
        sender = formataddr((lab.getName(), from_contact.getEmailAddress()))
        receiver = formataddr((encode_header(client.getName()), to_contact.getEmailAddress()))
        body = "Automatic email:\n"
        body += 'The shipment \"%s\" has been sent from the Biobank \"%s\".' % (self.Title(), lab.getName())
        self.send_mail(sender, receiver, subject, body) 
Example #13
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_quote_dump(self):
        self.assertEqual(
            utils.formataddr(('A Silly; Person', 'person@dom.ain')),
            r'"A Silly; Person" <person@dom.ain>') 
Example #14
Source File: cgtk_email.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((
        Header(name, 'utf-8').encode(),
        addr.encode('utf-8') if isinstance(addr, unicode) else addr)) 
Example #15
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_name_with_dot(self):
        x = 'John X. Doe <jxd@example.com>'
        y = '"John X. Doe" <jxd@example.com>'
        a, b = ('John X. Doe', 'jxd@example.com')
        self.assertEqual(utils.parseaddr(x), (a, b))
        self.assertEqual(utils.parseaddr(y), (a, b))
        # formataddr() quotes the name if there's a dot in it
        self.assertEqual(utils.formataddr((a, b)), y) 
Example #16
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_escape_backslashes(self):
        self.assertEqual(
            utils.formataddr(('Arthur \Backslash\ Foobar', 'person@dom.ain')),
            r'"Arthur \\Backslash\\ Foobar" <person@dom.ain>')
        a = r'Arthur \Backslash\ Foobar'
        b = 'person@dom.ain'
        self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b)) 
Example #17
Source File: email_constructor.py    From v2ex_signup with MIT License 5 votes vote down vote up
def _format_add(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr)) 
Example #18
Source File: sampleshipment.py    From baobab.lims with GNU General Public License v3.0 5 votes vote down vote up
def workflow_script_ship(self):
        #send the email
        lab = self.bika_setup.laboratory
        sender = formataddr((encode_header(lab.getName()), self.getFromEmailAddress()))

        client = self.getClient()
        receiver = formataddr((encode_header(client.getName()), self.getToEmailAddress()))

        subject = "Samples Shipped: %s" % self.Title()
        body = "Automatic email:\n"
        body += 'The samples \"%s\" has been shipped.' % self.getStringified(self.getSamplesList())
        body += 'This is an automatic email that indicates that sample shipment %s has been shipped.\n\n' % self.Title()
        self.send_mail(sender, receiver, subject, body)

        self.free_storage_locations() 
Example #19
Source File: shipment.py    From baobab.lims with GNU General Public License v3.0 5 votes vote down vote up
def workflow_script_collect(self):
        """ Executed after shipment ready for collection from the client
        """
        to_contact = self.getToContact()
        from_contact = self.getFromContact()
        client = to_contact.aq_parent
        subject = "Shipment ready for collection"
        sender = formataddr((encode_header(client.getName()), to_contact.getEmailAddress()))
        lab = self.bika_setup.laboratory
        receiver = formataddr((lab.getName(), from_contact.getEmailAddress()))
        body = "Automatic email:\n"
        body += 'The shipment \"%s\" sent to the client \"%s\" is ready for collection.' % (self.Title(), client.getName())
        self.send_mail(sender, receiver, subject, body) 
Example #20
Source File: send_mail.py    From You-are-Pythonista with GNU General Public License v3.0 5 votes vote down vote up
def sendMail():
    # 邮件主题/标题
    mail_title = 'Email Reminder'
    # 邮件正文
    mail_content = 'This is an email reminder from Python.'
    # 发件人邮箱账号
    Sender = '*********@qq.com'
    # 收件人邮箱账号
    Receiver = '***********@126.com'
    # 发送邮件正文内容
    msg = MIMEText(mail_content, "plain", 'utf-8')
    # 发送邮件主题/标题
    msg["Subject"] = Header(mail_title, 'utf-8')
    # 发件人姓名  
    msg["From"] = formataddr(['&娴敲棋子&', Sender])
    # 收件人姓名  
    msg["To"] = formataddr(['&娴敲棋子&', Receiver]) 
    
    try:
        # 邮箱的传输协议,端口默认25
        e = smtplib.SMTP("smtp.qq.com", 25)   
        # 登录邮箱,第二个参数为发件人的邮箱授权码
        e.login(Sender, 'xxxxxxxxx')
        # 发送邮件,参数依次:发件人、收件人、发送消息
        e.sendmail(Sender, [Receiver, ], msg.as_string())
        # 退出邮箱
        e.quit()
        print('Email Send Successful!')
    except Exception:
        print('Email Send Failed!') 
Example #21
Source File: agent_new.py    From OpsSystem with MIT License 5 votes vote down vote up
def sendemail(mess):
    from_addr='your email'
    password='your password'
    to_addrs=','.join(EMAIL_LIST)
    smtp_server='smtp.exmail.qq.com'
    msg=MIMEText(mess,'plain','utf-8')
    msg['From']=formataddr((Header('异常守护进程启动告警','utf-8').encode(),from_addr))
    msg['To']=formataddr((Header(u'System Admin','utf-8').encode(),to_addrs))
    msg['Subject']=Header('SA','utf-8').encode()
    server=smtplib.SMTP(smtp_server,25)
    server.set_debuglevel(0)
    server.login(from_addr,password)
    server.sendmail(from_addr,EMAIL_LIST,msg.as_string())
    server.quit() 
Example #22
Source File: email_with_mako.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name), addr)) 
Example #23
Source File: email_utils.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def send_password_reset(user):
    """
    Sends an email to the specified user to reset their password.

    Args:
        user: The user to email.
    """
    # Generate the user's email address
    toaddr = formataddr((user.display_name, user.email))

    # Build the subject
    subject = 'RAD Remedy - Password Reset Request'

    # Build the reset URL
    reset_url = current_app.config.get('BASE_URL') + \
        url_for('auth.reset_password', code=user.email_code)

    # Get the IP of the person requesting the reset
    request_ip = get_ip()

    # Build the text of the message
    message_text = render_template(
        'email/reset-password.txt',
        subject=subject,
        user=user,
        reset_url=reset_url,
        request_ip=request_ip)

    # Now build the HTML version
    message_html = render_template(
        'email/reset-password.html',
        subject=subject,
        user=user,
        reset_url=reset_url,
        request_ip=request_ip)

    send_email(toaddr, subject, message_text, message_html) 
Example #24
Source File: email_utils.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def send_confirm_account(user):
    """
    Sends an email to the specified user to confirm their account.

    Args:
        user: The user to email.
    """
    # Generate the user's email address
    toaddr = formataddr((user.display_name, user.email))

    # Build the subject
    subject = 'RAD Remedy - Confirm Account'

    # Build the confirmation URL
    confirm_url = current_app.config.get('BASE_URL') + \
        url_for('auth.confirm_account', code=user.email_code)

    # Build the text of the message
    message_text = render_template(
        'email/confirm-account.txt',
        subject=subject,
        user=user,
        confirm_url=confirm_url)

    # Now build the HTML version
    message_html = render_template(
        'email/confirm-account.html',
        subject=subject,
        user=user,
        confirm_url=confirm_url)

    send_email(toaddr, subject, message_text, message_html) 
Example #25
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_noquote_dump(self):
        self.assertEqual(
            utils.formataddr(('A Silly Person', 'person@dom.ain')),
            'A Silly Person <person@dom.ain>') 
Example #26
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_formataddr_does_not_quote_parens_in_quoted_string(self):
        addr = ("'foo@example.com' (foo@example.com)",
                'foo@example.com')
        addrstr = ('"\'foo@example.com\' '
                            '(foo@example.com)" <foo@example.com>')
        self.assertEqual(utils.parseaddr(addrstr), addr)
        self.assertEqual(utils.formataddr(addr), addrstr) 
Example #27
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_name_with_dot(self):
        x = 'John X. Doe <jxd@example.com>'
        y = '"John X. Doe" <jxd@example.com>'
        a, b = ('John X. Doe', 'jxd@example.com')
        self.assertEqual(utils.parseaddr(x), (a, b))
        self.assertEqual(utils.parseaddr(y), (a, b))
        # formataddr() quotes the name if there's a dot in it
        self.assertEqual(utils.formataddr((a, b)), y) 
Example #28
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_unicode_address_raises_error(self):
        # issue 1690608.  email.utils.formataddr() should be rfc2047 aware.
        addr = 'pers\u00f6n@dom.in'
        self.assertRaises(UnicodeError, utils.formataddr, (None, addr))
        self.assertRaises(UnicodeError, utils.formataddr, ("Name", addr)) 
Example #29
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_invalid_charset_like_object_raises_error(self):
        # issue 1690608.  email.utils.formataddr() should be rfc2047 aware.
        name = "H\u00e4ns W\u00fcrst"
        addr = 'person@dom.ain'
        # An object without a header_encode method:
        bad_charset = object()
        self.assertRaises(AttributeError, utils.formataddr, (name, addr),
            bad_charset) 
Example #30
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_quotes_unicode_names(self):
        # issue 1690608.  email.utils.formataddr() should be rfc2047 aware.
        name = "H\u00e4ns W\u00fcrst"
        addr = 'person@dom.ain'
        utf8_base64 = "=?utf-8?b?SMOkbnMgV8O8cnN0?= <person@dom.ain>"
        latin1_quopri = "=?iso-8859-1?q?H=E4ns_W=FCrst?= <person@dom.ain>"
        self.assertEqual(utils.formataddr((name, addr)), utf8_base64)
        self.assertEqual(utils.formataddr((name, addr), 'iso-8859-1'),
            latin1_quopri)