Python 发送邮件 --- 邮件(2)

"""
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000

SMTP 是发邮件的协议
POP3 是收邮件的协议

"""

class SendEmail(object):
    """
    Python内置对SMTP的支持,支持发送文本,html样式,还可以带附件。
    使用python发邮件,需要使用到两个模块,
    email 负责 构造邮件
    smtplib 负责发送邮件
    """
    @classmethod
    def send_first_email(self):
        """
        发送一个纯文本邮件
        """
        # 使用email模块 构造邮件
        from email.mime.text import MIMEText
        # 第一个参数,邮件正文
        # 第二个参数,_subtype='plain', Content-Type:text/plain,这个应该是一种规范吧?
        # 第三个参数 utf-8编码保证兼容
        msg = MIMEText("你害怕大雨吗?","plain","utf-8")
        # 添加信息防止失败,如果收件人 发件人 标题出现乱码情况, from email.header import Header等方法进行转码
        msg['From'] = "Tsun<[email protected]>" # 收件人看到的发件人信息
        msg['To'] = "xxxx<[email protected]>"   #
        from email.header import Header
        msg['Subject'] = "人生苦短,这是标题"

        # 发送email
        import smtplib
        # 邮件SMTP服务器,默认25端口
        server = smtplib.SMTP("smtp.163.com",25)
        server.set_debuglevel(1) # 这句话,可以打印出和SMTP交互的所有信息
        # 发送人的邮件和密码
        server.login("[email protected]", "xxxxxxx")
        # 发件人,收件人列表,msg.as_string()把MIMEText对象变成str
        server.sendmail("[email protected]", ["[email protected]"], msg.as_string())
        print("发送成功了")
        server.quit()
        print("退出")

if __name__ == "__main__":
    SendEmail.send_first_email()

"""
还可以发送html 带图片的文件,略

还可以文本和html混合发送
msg = MIMEMultipart('alternative')
msg['From'] = ...
msg['To'] = ...
msg['Subject'] = ...

msg.attach(MIMEText('hello', 'plain', 'utf-8'))
msg.attach(MIMEText('<html><body><h1>Hello</h1></body></html>', 'html', 'utf-8'))
# 正常发送msg对象...

smtp_server = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 剩下的代码和前面的一模一样:
server.set_debuglevel(1)
...




# 发送附件
# https://blog.csdn.net/qq_20417499/article/details/80566265
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication 

if __name__ == '__main__':
        fromaddr = '[email protected]'
        password = 'password'
        toaddrs = ['[email protected]', '[email protected]']

        content = 'hello, this is email content.'
        textApart = MIMEText(content)

        imageFile = '1.png'
        imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
        imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)

        pdfFile = '算法设计与分析基础第3版PDF.pdf'
        pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
        pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
    

        zipFile = '算法设计与分析基础第3版PDF.zip'
        zipApart = MIMEApplication(open(zipFile, 'rb').read())
        zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)

        m = MIMEMultipart()
        m.attach(textApart)
        m.attach(imageApart)
        m.attach(pdfApart)
        m.attach(zipApart)
        m['Subject'] = 'title'

        try:
            server = smtplib.SMTP('smtp.163.com')
            server.login(fromaddr,password)
            server.sendmail(fromaddr, toaddrs, m.as_string())
            print('success')
            server.quit()
        except smtplib.SMTPException as e:
            print('error:',e) #打印错误
"""

猜你喜欢

转载自blog.csdn.net/sunt2018/article/details/86624045