Today in the attempt to use Python to send mail, read a lot of tutorials on the Internet, I found that for beginners I am a bit complicated and the code is more troublesome, and there is not too many comments tell me what this is for, usage is what
This tutorial is very simple, but I have enough to deal with my daily work needs, as OPS, I want to be able to send the message and the correct display of the content is enough, do not need too many fancy things.
The preparation for the test is that I redirect the command output of W to a file under the virtual machine, as the message body sends the content.
W > Msg.log
[email protected] tmp]# cat Msg.log
02:48:50 up 10:11, 1 user, Load average:0.00, 0.00, 0.00
USER TTY from [email protected] IDLE jcpu PCPU
Root pts/0 192.168.178.1 02:48 0.00s 0.06s 0.00s W
[Email protected] tmp]#
Here's what Python is about:
#!/usr/bin/pythonimport smtplib #导入模块mailfrom = ' [email Protected] ' #定义发件人, recipient, Password mailto= ' [email protected] ' passwd= ' ABCDEFG ' subject= ' this is a test ' #定义主题body =open (' Msg.log '). Read () #读取文件的内容作为body信息msg = "" "from:%s #定义发邮件的格式TO:%ssubject:%s%s "" " % (Mailfrom, Mailto,subject,body) #把变量传入到格式中smtp =smtplib. SMTP () &nbsP; smtp.connect (' smtp.126.com ') #连接到126的邮箱服务器smtp. Login ( MAILFROM,PASSWD) #登陆邮箱smtp. SendMail (mailfrom,mailto,msg) #发送邮件
So that you can get the mail, but before you look at the results, you need to explain a few points.
After the format of MSG this variable is complete, it must be this:
>>> print msg From:[email protected] #必须不与上面留空行TO:[email protected]subject:this is a test #必须与上部分留空行 02:48:50 up 10:11, 1 user, load average: 0.00, 0.00, 0.00user tty FROM [email protected] idle jcpu pcpu whatroot pts/0 192.168.178.1 02:48 0.00s 0.06s 0.00s w
If you do not pay attention to these details, will cause the message to receive is likely to be no title or title confusion!
Also, MSG does not have to use my this string processing method, you can use other methods such as list and split,\n such a combination of generation, but the resulting format should be the same, that is, all roads through Rome ~ ~ I used a lazy way
This production environment should have more try-except to determine the success of the process, not given here!!
OK, check the results:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/53/75/wKioL1RoJEngwjiBAAEpsTSK5bw421.jpg "title=" screen shot 2014-11-16 12.08.46.png "alt=" Wkiol1rojengwjibaaepstsk5bw421.jpg "/>
This article is from the "to be a knowledgeable ops dog" blog, please be sure to keep this source http://kekeung.blog.51cto.com/2339469/1577112
Python's simplest way to send mail (without attachments)