So this is a very small post on how to send email in python where in there needs to be users in To, Cc and Bcc.
Let us say we need to send mail with the below details -
From address - abc@gmail.com
To address - def@gmail.com
Cc address - d@gmail.com, e@gmail.com
Bcc address - f@gmail.com
Email subject - test
Email Body - test body
smtp - smtp.gmail.com
port - 587
*please note the email random.
Based on the above below is the code and explanation is above each one of the lines
Let us say we need to send mail with the below details -
From address - abc@gmail.com
To address - def@gmail.com
Cc address - d@gmail.com, e@gmail.com
Bcc address - f@gmail.com
Email subject - test
Email Body - test body
smtp - smtp.gmail.com
port - 587
*please note the email random.
Based on the above below is the code and explanation is above each one of the lines
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 logging
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def sendemail(fromaddr,senderpwd,smtp,port,msgSubject,msgBody,toaddr,cc,bcc):
# instance of MIMEMultipart
msg = MIMEMultipart()
toaddr = toaddr
# storing the senders email address
msg['From'] = fromaddr
# storing the receivers email address
msg['To'] = toaddr
msg['Cc'] = cc
msg['Bcc']= bcc
# storing the subject
msg['Subject'] = msgSubject
# string to store the body of the mail
body = msgBody
msg.attach(MIMEText(body, 'plain'))
# creates SMTP session
s = smtplib.SMTP(smtp, port)
# start TLS for security
s.starttls()
# Authentication
s.login(fromaddr, senderpwd)
# Converts the Multipart msg into a string
text = msg.as_string()
msg.attach(body)
# sending the mail
s.sendmail(fromaddr, [toaddr,cc,bcc], text)
# terminating the session
s.quit()
def main():
sendemail(' abc@gmail.com','randaompawd','smtp.gmail.com',587,'test','body test','def@gmail.com','d@gmail.com,e@gmail.com','f@gmail.com')
if __name__=="__main__":
main()
No comments:
Post a Comment