前几天需要服务端发送邮件的脚本,发现直接用sendmail相对来说复杂,大才小用了,因为我只需要一个发送的功能即可。于是查查改改,很容易弄了一个。
python弄这些简单的email client,http client, tcp client之类的真的很方便,而且windows上也可以直接执行。
# Import smtplib for the actual sending function
import sys
import getopt
import smtplib
sender = 'sender@xxxx'
# If there are more than one receiver, you need to ganerate a list.
# receiver = ['a@xxxx','b@xxxx']
receiver = ['receiver@xxxx']
server = 'smtp.mail.xxxx.cn'
port = '25'
pwd = 'password'
COMMASPACE = ', '
# Import the email modules we'll need
from email.mime.text import MIMEText
def usage():
usageStr = '''Usage: SendEmail -c mail_content'''
print usageStr
def main(argv):
# Get the Email content in the "-c" argv
try:
opts, args = getopt.getopt(argv, "c:")
except getopt.GetoptError:
usage()
sys.exit(2)
content = ''
for opt, arg in opts:
if opt == '-c':
content = arg
print content
msg = MIMEText(content)
msg['Subject'] = 'this is the subject'
msg['From'] = sender
msg['To'] = COMMASPACE.join(receiver)
s = smtplib.SMTP(server, port)
s.ehlo()
s.login(sender, pwd)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
if __name__=="__main__":
main(sys.argv[1:])
python版本比较老时会遇到这种报错:
ImportError: No module named mime.text
解决办法:
将这句from email.mime.text import MIMEText
改为:
from email.MIMEText import MIMEText
from email.Header import Header