Python 使用Gmail傳送郵件
阿新 • • 發佈:2019-01-07
前言:2014-05-22記錄在hi baidu上,現在移過來
使用python向gmail發郵件
"""
傳送郵件
1: 需要提供傳送者的郵件、密碼;接收者地址;
2:步驟:
a:Login 失敗說明無法登陸;
b:登入成功則可以傳送郵件;
c:退出
"""
class SendMailToServer():
"""docstring for SendMailToServer"""
def __init__(self, fromAddress, password, toAddress) :
# my test mail
self.mail_username = fromAddress
self.mail_password = password
self.from_addr = self.mail_username
self.to_addrs = toAddress
# HOST & PORT
self.HOST = 'smtp.gmail.com'
self.PORT = 25
# Create SMTP Object
self.smtp = smtplib.SMTP()
def Login(self):
# 列印除錯資訊
self.smtp.set_debuglevel(1)
try:
self.smtp.connect( self.HOST, self.PORT )
except Exception, e:
print e, 'connect failed ...'
return False
# gmail uses ssl
self.smtp.starttls()
# login with username & password
try:
print 'loginning ...'
self.smtp.login( self.mail_username, self.mail_password )
except Exception, e:
print e, 'login faild ...'
return False
return True