SWDesk/Firmware

[Python] Example for Sending Gmail with Attached Files

bizmaker 2021. 1. 18. 00:13

 

 

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

class cBMailer:
    def __init__(self):
        pass

    def SendMail_BluehostTest(self):

        passWd = 'PASSWORD'
        userAddress = 'USERADDRESS'

        smtp = smtplib.SMTP('mail.DOMAIN.net', 465)
        smtp.starttls()
        smtp.login(userAddress, passWd)
        print('10')

        testNumber = 111
        msg = MIMEMultipart()
        msg['Subject'] = '[테스트]Subject'+str(testNumber)
        msg.attach(MIMEText('[Test]바디'+str(testNumber), 'plain'))
        print("11")

        fileName = "친환경+ 제조_20201229101101.xlsx"

        attachment = open(fileName, 'rb')
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('content-Disposition', 'attachment; filename='+fileName)
        msg.attach(part)
        print('12')

        smtp.sendmail(userAddress, 'RECEIVER', msg.as_string())
        smtp.quit()

    def SendMail_GmailTest(self):

        passWd = 'PASSWORD'
        userAddress = 'USRADDRESS'

        smtp = smtplib.SMTP('smtp.gmail.com', 587)
        smtp.starttls()
        smtp.login(userAddress, passWd)
        print('10')

        testNumber = 111
        msg = MIMEMultipart()
        msg['Subject'] = '[테스트]Subject'+str(testNumber)
        msg.attach(MIMEText('[Test]바디'+str(testNumber), 'plain'))
        print("11")

        fileName = "친환경+ 제조_20201229101101.xlsx"

        attachment = open(fileName, 'rb')
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=fileName)
        msg.attach(part)
        print('12')

        smtp.sendmail(userAddress, 'RECEIVER', msg.as_string())
        smtp.quit()


반응형