Python Send Email



#### # Sending email for single user######

import smtplib
from email.mime.text import MIMEText
body='testing body'
subject = "Test Email Subject"
sender = "sk9775589@gmail.com"
recipients = ["sabhajeetkumar1@gmail.com",'sk9775589@gmail.com']
password = "qwsnxvnheoqyauij"

def send_email(subject, body, sender, recipients, password):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:
smtp_server.login(sender, password)
smtp_server.sendmail(sender, recipients, msg.as_string())

print("Message sent!")

send_email(subject, body, sender, recipients, password)

                                #### # Sending email to multiple user using File ######

import pandas as pd
df=pd.read_csv(r"C:\Users\Home\Downloads\apple_products2.csv", usecols=['ID','msg','sub'],low_memory=True)
df=pd.DataFrame(df)

import smtplib
from email.mime.text import MIMEText

subject = "Test Email Subject"
sender = "sk9775589@gmail.com"
#recipients = ["sabhajeetkumar1@gmail.com"]
password = "qwsnxvnheoqyauij"

def send_email(subject, body, sender, recipients, password):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:
smtp_server.login(sender, password)
smtp_server.sendmail(sender, recipients, msg.as_string())

print("Message sent!")

for x in range(len(df)):
send_email(df.loc[x,'sub'], df.loc[x,'msg'], sender, df.loc[x,'ID'], password)


######### Explaination about file loading and dataframe ########
import pandas as pd
body1 = pd.read_csv(r"C:\Users\Home\Downloads\apple_products.csv", usecols=['Product Name','Product URL'],low_memory=True)
body1=pd.DataFrame(body1)

for x in range(len(body1)):
print(body1.loc[x,'Product Name'],body1.loc[x,'Product URL'])

############# Sending Email using Error Handler ##############
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmailUser = 'sk9775589@gmail.com'
gmailPassword = 'qwsnxvnheoqyauij'
recipient = 'sabhajeetkmr9@gmail.com'

message = f"""
Type your message here...
"""

msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Subject here..."
msg.attach(MIMEText(message))

try:
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print ('Email sent!')
except:
print ('Something went wrong...')



Comments