专题:wxpython中文教程
例子:
#!/usr/bin/python
#coding=utf-8
#tom.py
import wx
import smtplib
EMAIL_ADDRESS = 'laxers@gmail.com'
PASSWORD = **********
class Tom(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title,
wx.DefaultPosition, wx.Size(400, 420))
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, '自:')
st2 = wx.StaticText(panel, -1, '到:')
st3 = wx.StaticText(panel, -1, '主题:')
self.tc1 = wx.TextCtrl(panel, -1, 'laxers@gmail.com',
size=(180, -1))
self.tc2 = wx.TextCtrl(panel, -1, size=(180, -1))
self.tc3 = wx.TextCtrl(panel, -1, size=(180, -1))
self.write = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
button_send = wx.Button(panel, 1, '寄出')
hbox1.Add(st1, 0, wx.LEFT, 10)
hbox1.Add(self.tc1, 0, wx.RIGHT, 20)
hbox2.Add(st2, 0, wx.LEFT, 10)
hbox2.Add(self.tc2, 0, wx.RIGHT, 35)
hbox3.Add(st3, 0, wx.LEFT, 10)
hbox3.Add(self.tc3, 0, wx.RIGHT)
vbox.Add(hbox1, 0, wx.TOP, 10)
vbox.Add(hbox2, 0, wx.TOP, 10)
vbox.Add(hbox3, 0, wx.TOP, 10)
vbox.Add(self.write, 1, wx.EXPAND|wx.TOP|wx.RIGHT|wx.LEFT, 15)
vbox.Add(button_send, 0, wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, 20)
self.Bind(wx.EVT_BUTTON, self.OnSend, id=1)
panel.SetSizer(vbox)
self.Center()
def OnSend(self, event):
sender = self.tc1.GetValue()
recipient = self.tc2.GetValue()
subject = self.tc3.GetValue()
text = self.write.GetValue()
header = u"From: %srnTo: %srnSubject: %srnrn"
% (sender, recipient, subject)
message = header + text
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(EMAIL_ADDRESS, PASSWORD)
server.sendmail(sender, recipient, message)
server.quit()
dlg = wx.MessageDialog(self, '电子邮件发送成功', '成功',
wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
except smtplib.SMTPException, error:
dlg = wx.MessageDialog(self, '发送电子邮件失败', '错误',
wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
class MyApp(wx.App):
def OnInit(self):
dlg = Tom(None, -1, 'Tom')
dlg.ShowModal()
dlg.Destroy()
return True
app = MyApp(0)
app.MainLoop()
要导入(import) smtp 模块来处理电子邮件.
import smtplib
发自(From)、发往(To)以及主题(Subject)选项必须用回车(return)和新行(newline)分开. 这个奇怪的规定是由RFC 821规范所要求的.
所以,必须遵守这个规定.
接着,创建了一个 SMTP 连接. 在这里指定你的设置. 每个 ISP 都会提供给你相应的 POP 和 SMTP 服务器名字.
在这个例子中, 指定了“smtp.gmail.com”以及端口号 587.
通过调用 sendmail() 方法,邮件就发送出去了. 最后,要用 quit() 方法来退出连接.