Linux Programmer | RHCE | RHCSA

Search This Blog

Send mail with attachment.

from datetime import date
import datetime
import time
import smtplib
import os
import sys
import mysql.connector
import commands
import xlwt
import pandas.io.sql as sql
from email.mime.multipart import MIMEMultipart
from mysql.connector import Error
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
class Sendmail:
   def __init__(self):
    print("Sending mail ......")
      cc = ['purval1992@gmail.com']
         fromaddr="alert@trakzee.com"
    today = date.today()
         if not os.path.exists('mycontacts1.txt'):
        os.system('echo "mail@gmail.com" >mycontacts1.txt')
         with open("mycontacts1.txt", "r") as a_file:
            for line in a_file:
               toaddr = line.strip()
               print("Sending mail to " + toaddr)
                  s = smtplib.SMTP('smtp-server-address', 587)
                   s.starttls()
                   s.login("smtp-server-username","smtp-server-password")

            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = toaddr
            msg['Subject'] = "attachment mail"
            body = 'this mail is for testing'
            msg.attach(MIMEText(body, 'plain'))
            filename = "test.txt"
            filepath = "/home/script/test.txt"
            attachment = open(filepath, "rb")
            p = MIMEBase('application', 'octet-stream')
            p.set_payload((attachment).read())
            encoders.encode_base64(p)
            p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
            msg.attach(p)
            text = msg.as_string()
            toaddrs = [toaddr] + cc
            s.sendmail(fromaddr, toaddrs, text)
            s.quit()



dataf = Sendmail()
dataf

No comments:

Post a Comment

Gitlab_CICD_Sample Deployment

Gitlab CICD Stages: build - Create build of project. - If it is docker project which contains dockerfile then, create docker image - push in...