python之(改写成了类)用smtplib模块实现第三方smtp发送邮件

本文介绍了一个使用Python的smtplib及email.mime模块实现邮件发送的功能性类。该类能够设置邮件主题、正文并附加文件,同时提供了发送邮件的方法。通过实例演示了如何发送带有附件的测试邮件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#_*_ 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>
            ''' % message
        html = MIMEText(html_msg, 'html''utf-8')
        Sendmail.msg.attach(html)
 
    def files(self,path,filenames):
        files = path + filenames
        att = MIMEText(open(files, 'rb').read(), 'base64''utf-8')
        att["Content-Type"= 'application/octet-stream'
        att["Content-Disposition"= 'attachment; filename=%s' % 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__":
 
    = Sendmail('xxxx.xxxx.com','xxxxx@xxxx.com','xxxxxx'#实例化一个发送邮件的对象
    a.mess('hello world','this is test mail')   #定义主题,消息
    a.files('/var/log/','syslog.2.gz'#这是发送邮件 定义路径、文件名
    a.send('xxxx@qq.com')  #收件人


本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1875021


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值