雪影风清

雪地见影,风中见清

0%

python使用smtplib和email模块发送邮件

1. 准备环境

1
2
3
# 由于python2.7 内含smtplib模块,这里只需要安装email模块
# 要查看已经安装的python模块可以使用命令:pydoc modules
pip install email

2. 脚本实例

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
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/python

#It's a test to send mail by mail.163.com

from __future__ import print_function
import smtplib
from email.mime.text import MIMEText

SMTP_SERVER = "smtp.163.com"
SMTP_PORT = 465

def send_mail(user, pwd, to, subject, text):
msg = MIMEText(text)
msg['From'] = user
msg['To'] = to
msg['subject'] = subject

smtp_server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
print('Connecting To Mail Server.')

try:
smtp_server.ehlo()
print('Starting Encrypted Section.')

smtp_server.starttls()
smtp_server.ehlo()
print('Logging Into Mail Server')

smtp_server.login(user, pwd)
print('Sending Mail.')
smtp_server.sendmail(user, to, msg.as_string())
except Exception as err:
print('Sending Mail Failed: {0}'.format(err))
finally:
smtp_server.quit()
def main():
send_mail('blowhunter@163.com', '****', 'blowhunter@163.com', 'It is a test from my python poject', 'You get me!')

if __name__ == '__main__':
main()