rfc822parseaddr()函数在Python中的作用和示例讲解
The rfc822parseaddr() function in Python is used to parse email addresses in RFC 822 format. It takes an email address string as input and returns a tuple containing the name and address parts of the email address.
Here is an example to demonstrate the usage of rfc822parseaddr():
import rfc822
email1 = 'John Doe <john.doe@example.com>'
email2 = 'jane.doe@example.com'
name1, address1 = rfc822.parseaddr(email1)
name2, address2 = rfc822.parseaddr(email2)
print(f'Name 1: {name1}')
print(f'Address 1: {address1}')
print(f'Name 2: {name2}')
print(f'Address 2: {address2}')
Output:
Name 1: John Doe Address 1: john.doe@example.com Name 2: Address 2: jane.doe@example.com
In the above example, the rfc822parseaddr() function is used to parse two email addresses. email1 contains a name and address in the RFC 822 format, while email2 only contains an address. The function separates the name and address parts and returns them as separate values for further processing.
As you can see from the output, for email1, the function successfully extracts the name 'John Doe' and the address 'john.doe@example.com'. However, for email2, since it doesn't contain a name, the function returns an empty string for the name2 variable.
The rfc822parseaddr() function can be useful when dealing with email addresses in different formats, especially when there is a need to extract specific parts such as names or domain names.
It is important to note that the rfc822 module was deprecated in Python 2.0 and removed in Python 3.0. It is recommended to use the email module instead for parsing email addresses.
