fgdfg 发表于 2015-12-1 07:36:54

python发送文本邮件

1 #!/usr/bin/env python
2 #coding=utf-8
3 #Author: Ca0Gu0

4 import time
5 import smtplib
6 from email.mime.text import MIMEText
7
8 class MailCli(object):
9   def __init__(self):
10         self.s = smtplib.SMTP()             #类实例化
11         
12   def connect(self, host=None, port=25):
13         self.s.connect(host, port)          #连接邮件服务器
14         
15   def login(self, user=None, passwd=None):
16         self.user = user
17         self.s.login(user, passwd)          #登陆帐户跟密码
18         
19         
20   def send(self, subject=None, content=None, to=None):
21         froms = self.user+'<%s>' %(self.user)
22         msg = MIMEText(content)             #处理发件内容
23         msg['Subject'] = subject            #处理发件主题
24         msg['From'] = froms               #处理发件人地址
25         msg['To'] = to                      #处理收件人地址   
26         self.s.sendmail(froms, to, msg.as_string())   #发送邮件内容
27         return "OK"
28         
29   def close(self):
30         self.s.close()                                     #退出登陆
31         return '0'                                        #显示发信成功
32
33
34 if __name__ == "__main__":
35   host = "mail.xxx.com"
36   port = 25
37   user = "caoguo@xxx.com"
38   passwd = "password"
39   to = "caoguo@163.com"
40
41   r=MailCli()
42   r.connect(host=host,port=port)
43   r.login(user=user, passwd=passwd)
44   
45   for i in range(10):                                  #连续发生10封邮件
46         
47         subject = "Testing SMTP Authentication "+ str(i)
48         content = "This mail tests SMTP Authentication" + str(i)
49         returns = r.send(subject=subject, content=content, to=to)
50         print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())),returns
51   r.close()
  
页: [1]
查看完整版本: python发送文本邮件