首頁  >  文章  >  後端開發  >  詳解python之用smtplib模組實作第三方smtp發送郵件的實例

詳解python之用smtplib模組實作第三方smtp發送郵件的實例

高洛峰
高洛峰原創
2017-03-26 17:57:161114瀏覽

這篇文章主要為大家詳解python之用smtplib模組實現第三方smtp發送郵件的實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

#_*_ coding:utf-8 _*_
import  smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
 
class Sendmail:
 
    local_hostname = ['toby-ThinkPad-T430shhhh']
    msg = MIMEMultipart('related')
 
    def __init__(self,smtp_server,mail_user,mail_pass):
        self.smtp_server = smtp_server
        self.mail_user = mail_user
        self.mail_pass = mail_pass
 
    def mess(self,theme,message):
        Sendmail.msg['Subject'] = theme  # 邮件主题
        html_msg = '''
                <html><head><body>
                <p>%s</p>
                </body></head></html>
            &#39;&#39;&#39; % message
        html = MIMEText(html_msg, &#39;html&#39;, &#39;utf-8&#39;)
        Sendmail.msg.attach(html)
 
    def files(self,path,filenames):
        files = path + filenames
        att = MIMEText(open(files, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;utf-8&#39;)
        att["Content-Type"] = &#39;application/octet-stream&#39;
        att["Content-Disposition"] = &#39;attachment; filename=%s&#39; % filenames
        Sendmail.msg.attach(att)
 
    def send(self,receiver):
        smtp = smtplib.SMTP()
        smtp.connect(self.smtp_server)
        smtp.ehlo(self.local_hostname)  # 使用ehlo指令向smtp服务器确认身份
        smtp.starttls()  # smtp连接传输加密
        smtp.login(self.mail_user, self.mail_pass)
        smtp.sendmail(self.mail_user, receiver, Sendmail.msg.as_string())
        smtp.quit()
if __name__ == "__main__":
 
    a = Sendmail(&#39;xxxx.xxxx.com&#39;,&#39;xxxxx@xxxx.com&#39;,&#39;xxxxxx&#39;) #实例化一个发送邮件的对象
    a.mess(&#39;hello world&#39;,&#39;this is test mail&#39;)   #定义主题,消息
    a.files(&#39;/var/log/&#39;,&#39;syslog.2.gz&#39;) #这是发送邮件 定义路径、文件名
    a.send(&#39;xxxx@qq.com&#39;)  #收件人

以上是詳解python之用smtplib模組實作第三方smtp發送郵件的實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn