Detailed explanation of how to use the smtplib module in Python to implement third-party SMTP mail sending examples

高洛峰
Release: 2017-03-26 17:57:16
Original
991 people have browsed it

This article mainly explains in detail how to use the smtplib module in Python to implement third-party SMTP mail sending. It has certain reference value. Interested friends can refer to it

#_*_ 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 = '''
                
                

%s

''' % 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__": a = Sendmail('xxxx.xxxx.com','[email protected]','xxxxxx') #实例化一个发送邮件的对象 a.mess('hello world','this is test mail') #定义主题,消息 a.files('/var/log/','syslog.2.gz') #这是发送邮件 定义路径、文件名 a.send('[email protected]') #收件人
Copy after login

The above is the detailed content of Detailed explanation of how to use the smtplib module in Python to implement third-party SMTP mail sending examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!