Python发送邮件

python 发送邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
#
#
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))
#
#
fromAddr = "xxxx@xx.com"
toAddr = ["xxxx@xx.com"]
serverIp = "xx.xx.xx.xx"
message = MIMEText("email content:hello", _charset="utf-8")
message['Subject'] = Header("email title", charset="utf-8").encode()
message['From'] = _format_addr('xxx <%s>' % fromAddr)
message['To'] = _format_addr('xxx <%s>' % toAddr)
# send email
try:
server = smtplib.SMTP(serverIp, 25)
# username = "xxxx"
# password = "xxxxxxxx"
# server.login(user=username, password=password)
server.sendmail(fromAddr, toAddr, message.as_string())
server.quit()
print "email send success"
except smtplib.SMTPException:
print "email send error"