Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
3.4 kB
1
Indexable
Never
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import sys
import os
import socket
from airflow.hooks.base import BaseHook




def sendmail(subject, body, to_mail_ids,emailBodyType, cc_mail = None, bcc_mail= None,file_attachment=None,sender_pass=None):

    try:
        conn = BaseHook.get_connection("email_config")
        hostMail=conn.host
        fromMail=conn.schema
        mailPort=conn.port
        mail_content = body
        #sender_address = sender_mail
        sender_pass = sender_pass
        receiver_address = to_mail_ids
        #host = host
        #port = port
        cc_mail_ids = cc_mail
        bcc_mail_ids = bcc_mail
        if cc_mail_ids and bcc_mail_ids :
            final_mail_ids = receiver_address + cc_mail_ids + (str)bcc_mail_ids.split(",")
            final_mail_ids =" , ".join(final_mail_ids)
            final_mail_ids = final_mail_ids.split(",")
            print(final_mail_ids)
        else:
            final_mail_ids =" , ".join(receiver_address)
            final_mail_ids = final_mail_ids.split(",")
            print(final_mail_ids)
        # Setup the MIME
        message = MIMEMultipart()
        message['From'] = fromMail
        message['To'] = " , ".join(receiver_address)
        message['Subject'] = str(socket.gethostbyname(socket.gethostname())) + "-" + subject
        if cc_mail_ids:
            message['Cc'] = " , ".join(cc_mail_ids)
        if bcc_mail_ids:
            message['Bcc'] = " , ".join(bcc_mail_ids)

        # The body and the attachments for the mail
        message.attach(MIMEText(mail_content, emailBodyType))
        
        if file_attachment:
            if file_attachment != "" and os.path.exists(file_attachment):
                # open the file to be sent
                filename = os.path.basename(file_attachment)
                attachment = open(file_attachment, "rb")

                # instance of MIMEBase and named as p
                p = MIMEBase('application', 'octet-stream')

                # To change the payload into encoded form
                p.set_payload((attachment).read())

                # encode into base64
                encoders.encode_base64(p)

                p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

                # attach the instance 'p' to instance 'msg'
                message.attach(p)

        text = message.as_string()

        # Create SMTP session for sending the mail
        session = smtplib.SMTP(hostMail, mailPort)  # use gmail with port
        # session.starttls()  # enable security
        # session.login(sender_address, sender_pass)  # login with mail_id and password
        session.sendmail(fromMail, final_mail_ids, text)
        session.quit()
        return True
    except Exception as dbExcp:
        print("Exception - {} . Line No - {} ".format(str(dbExcp), str(sys.exc_info()[-1].tb_lineno)), None)
        return False


if __name__ == '__main__':
    mailStatus = sendmail(hostMail, mailPort, fromMail, '', 'email test', 'hi',
                          'veerendrakumar.meka@tcs.com', '', '', '', 'plain')
    if mailStatus:
        print('Mail Sent')
    else:
        print('Mail Sending Failed :(')