使用python开发一个简单的邮件发送脚本

使用python开发一个简单的邮件发送脚本

  • 废话不多说,直接上代码demo
 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*- 
import time
import socket
import httplib
import json
import datetime
import os
import commands
import subprocess

import sys
#========================================== 
# 导入smtplib和MIMEText 
#========================================== 
from email.mime.text import MIMEText 
import smtplib 
#========================================== 
# send to,split by','
#========================================== 
mailto_list=["xxx@qq.com"] 
#========================================== 
#========================================== 
mail_host="smtp.qq.com"
mail_user="QQ number"
mail_pass="QQ pass key"
mail_postfix="qq.com"
#========================================== 
# 发送邮件 
#========================================== 
def send_mail(to_list,sub,content): 
  ''''' 
  to_list:des email address
  sub:subject
  content:content
  send_mail("qq@qq.com","sub","content") 
  '''
  me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
  msg = MIMEText(content) 
  msg['Subject'] = sub 
  msg['From'] = me 
  msg['To'] = ";".join(to_list) 
  try: 
    s = smtplib.SMTP() 
    s.connect(mail_host) 
    s.starttls() 
    s.login(mail_user,mail_pass) 
    s.sendmail(me, to_list, msg.as_string()) 
    s.close()
    print("ok")
    return True
  except Exception, e:
    print(e)
    return False

        
if __name__ == "__main__":
    print os.path.abspath(os.curdir)
    argc = len(sys.argv)
    if argc != 3:
        print("argc:",argc)
        sys.exit()
    title = sys.argv[1]
    body = sys.argv[2]
    print("title,body:",title,body)
    if title != "" and body != "":
        send_mail(mailto_list,title,body)
        #send_mail(mailto_list,"在线人数",players.decode("ascii").encode("utf-8"))