Send Email to more then 1 recipient from script - python-3.x

i have a file this is the code in the file
import smtplib
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "foo#bar.com"
toaddr = sys.argv[7]
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = sys.argv[7]
subject = "Call Recordings Caller: "+ sys.argv[4] + " Time: " + sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3]
msg['Subject'] = subject
body = "You have a new call recording to listen to \n\nThe call date and time was %s %s %s \n\n The call was from %s \n\nThe call was to %s \n\n\nPlease see the attached file" %(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5])
msg.attach(MIMEText(body, 'plain'))
filename = sys.argv[6]
recoding_file = "/tmp/recordings/" + filename
attachment = open(recoding_file, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.sendgrid.net', 587)
server.starttls()
server.login("username", "encrypted")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
if i am getting in sys.argv[7] "me#foo.com,foo#me.com"
it will only send the email to the first email in the list
how can i make it so it sends it to all

Make your message a list then run a loop while using sendmail.
msg = [recipient1,recipient2]
for i in msg:
server.sendmail(fromaddr, toaddr, i)

Related

smtplib sending duplicate emails

I have been sending excel files automatically using the smtplib package and a linux machice a using scheduled crontab job. I recently updated the email distribution list and now instead of the email sending once its sending 4 times. Any help with this would be hugely appreciated!
Here's my code:
import smtplib
from email.message import EmailMessage
def Emailer():
files = ['file1.csv', 'file2.csv', 'file3.csv', 'file.log']
new_attach = [f"file1{today}.csv",f"file2{today}.csv",'file3.csv', 'file.log' ]
new_ref = {orig_file: new_file for orig_file, new_file in zip(files, new_attach)}
msg = EmailMessage()
msg['Subject'] = "Subject"
msg['From'] = 'from#from.com'
msg['To'] = ['user1#user.com', 'user2#user.com', 'user3#user.com', 'user4#user.com']
msg['Cc'] = ['user5#user.com', 'user6#user.com', 'user7#user.com', 'user8#user.com', 'user9#user.com', \
'user11#user.com', 'user111#user.com', 'user1111#user.com']
msg.set_content( f""" <p>Message content here!</p>""", subtype='html')
for filename in files:
with open(filename, 'rb') as file:
file_data = file.read()
new_name = new_ref[file.name]
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=new_name)
try:
with smtplib.SMTP('sendsmtp.server.com', 25) as s:
s.send_message(msg)
# s.set_debuglevel(2)
print('email has been sent')
except Exception as ex:
print(ex, "Message was not sent!")

My email sender wont add a email body message only a subject line in python

Importing all the necessary requirements
from smtplib import SMTP
from my_email import email_mine , password_mine
from email_addresses import email1, email2
smtp_port = SMTP("smtp.gmail.com", 587)
smtp_port.ehlo()
smtp_port.starttls()
smtp_port.login(email_mine , password_mine)
creating body of message
subject = input("What is the Subject of this Mail?: ")
body = input("What is your message?: ")
final_message = f"Subject: {subject} \n \n {body}"
#list of emails
address_list = [email1, email2]
smtp_port.sendmail(email_mine, address_list, final_message)
print("Email Sent")
smtp_port.quit()

Sending Google Invites using the code below. When I sent the invite I just get a plain invite, with one line for body and no accept button

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import Encoders
import os,datetime
CRLF = "Hi This is the contet\r Welcome and thanks\n"
login = "login#gmail.com"
password = "password"
attendees = ["someone#gmail.com","someone1#gmail.com"]
organizer = "ORGANIZER;CN=organiser:mailto:first"+CRLF+" #gmail.com"
fro = "Abhijith Anil Vamadev <aavamadev#gmail.com>"
ddtstart = datetime.datetime.now()
dtoff = datetime.timedelta(days = 1)
dur = datetime.timedelta(hours = 1)
ddtstart = ddtstart +dtoff
dtend = ddtstart + dur
dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ")
dtstart = ddtstart.strftime("%Y-%m-%d T%:H%:M%SZ")
dtend = dtend.strftime("%Y-%m-%d T%:H%:M%SZ")
description = "DESCRIPTION: test invitation from pyICSParser"+CRLF
attendee = ""
for att in attendees:
attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-
PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE"+CRLF+" ;CN="+att+";X-NUM-GUESTS=0:"+CRLF+"
mailto:"+att+CRLF
ical ="BEGIN:VCALENDAR"+CRLF+"PRODID:pyICSParser"+CRLF+"VERSION:2.0"+CRLF+"CALSCALE:GREGORIAN"+CRLF
ical+="METHOD:REQUEST"+CRLF+"BEGIN:VEVENT"+CRLF+"DTSTART:"+dtstart+CRLF+"DTEND:"+dtend+CRLF+"DTSTAMP:"+dtstamp+CRLF+organizer+CRLF
ical+= "UID:FIXMEUID"+dtstamp+CRLF
ical+= attendee+"CREATED:"+dtstamp+CRLF+description+"LAST-MODIFIED:"+dtstamp+CRLF+"LOCATION:"+CRLF+"SEQUENCE:0"+CRLF+"STATUS:CONFIRMED"+CRLF
ical+= "SUMMARY:test "+ddtstart.strftime("%Y%m%d # %H:%M")+CRLF+"TRANSP:OPAQUE"+CRLF+"END:VEVENT"+CRLF+"END:VCALENDAR"+CRLF
eml_body = "Email body visible in the invite of outlook and outlook.com but not google calendar"
eml_body_bin = "This is the email body in binary - two steps"
msg = MIMEMultipart('mixed')
msg['Reply-To']=fro
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "Sample Invite for Something "+dtstart
msg['From'] = fro
msg['To'] = ",".join(attendees)
part_email = MIMEText(eml_body,"html")
part_cal = MIMEText(ical,'calendar;method=REQUEST')
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
ical_atch = MIMEBase('application/ics',' ;name="%s"'%("invite.ics"))
ical_atch.set_payload(ical)
Encoders.encode_base64(ical_atch)
ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"'%("invite.ics"))
eml_atch = MIMEText('', 'plain')
Encoders.encode_base64(eml_atch)
eml_atch.add_header('Content-Transfer-Encoding', "")
msgAlternative.attach(part_email)
msgAlternative.attach(part_cal)
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(login, password)
mailServer.sendmail(fro, attendees, msg.as_string())
mailServer.close()
I got this code from Sending Meeting Invitations With Python. I am unsure how to use it and want to send meeting invites. But I don't get a meeting invite with an accept button. I just get an invite with "Email body visible in the invite of outlook and outlook.com but not google calendar". Please help.

Problem with sendmail(email, send_to_email, msg.as_string())

I'm trying to attach and send multiple attachments to list of emails individually
import smtplib
import openpyxl
import os.path
from email import encoders
from openpyxl import load_workbook
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
email_source_workbook = load_workbook(filename=r'C:\Users\Name\Desktop\final mailer\mail list.xlsx')
curr_sheet = email_source_workbook['ml']
attachment_location = [r'C:\Users\Name\Desktop\final mailer\at1.txt']
row_len = curr_sheet.max_row
email = 'example#email.com'
password = 'pswrd'
subject = 'test subj' #Subject
message = '''this
is test
mail
ok?
'''
msg = MIMEMultipart()
with smtplib.SMTP('smtp-mail.outlook.com', 587) as svr:
print("Initializing the server")
svr.ehlo()
svr.starttls()
svr.ehlo()
svr.login(email, password)
print("login sucessful")
for curr_attachment in attachment_location:
name_of_attachment = os.path.basename(curr_attachment)
attachment_payload = MIMEBase('application' , "octet-stream")
attachment_payload.set_payload(open(curr_attachment, "rb").read())
encoders.encode_base64(attachment_payload)
attachment_payload.add_header('Content-Disposition', 'attachment' , filename=name_of_attachment)
for i in range(1 , row_len+1):
print("###################")
send_to_email = curr_sheet.cell(row = i, column = 1).value
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
svr.sendmail(email, send_to_email, msg.as_string())
svr.quit()
i can send the mail but the problem is for example there are 3 email addresses in the excel file
it will send the first mail to the first recipient
perfectly fine
then in the second mail it'll send it to the second and first recipient with the attachment + the wole body of mail as one more attachment
and to the third it will send to the first two recipients with the third with the original attachment with two same attachments that are the body of the mail. it will go on so fourth with n number of email addresses. i.e. 10 mail id and on the 10th mail the 10th recipient with all the previous 9 and 10 attachments.
found the solution
msg = MIMEMultipart()
should be in
for i in range(1 , row_len+1):
print("###################")
send_to_email = curr_sheet.cell(row = i, column = 1).value
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject
msg = MIMEMultipart()
msg.attach(MIMEText(message, 'plain'))
svr.sendmail(email, send_to_email, msg.as_string())

windows file directory path in Python

Can anyone please help me, I'm a newbie, I have a bit of code which I'm working on and I'm struggling with the file directory path. I have found other examples and tried them as shown below. The Python code is to email out a file called 'myfile.txt' form the folder 'F:\D\OneDrive\Python\Spyder\test'.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
#sender's address
fromaddr = "username#gmail.com"
#receiptent's email address
toaddr = "username2#gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Python test"
body = "Did it work Sam?"
msg.attach(MIMEText(body, 'plain'))
filename = "myfile.txt"
attachment = open("F:\D\OneDrive\Python\Spyder\test", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
And I get this error -
PermissionError: [Errno 13] Permission denied:
b'F:\\D\\OneDrive\\Python\\Spyder\\test'
If I change the line to -
attachment = open("F:\D\OneDrive\Python\Spyder\test\", "rb")
I get -
attachment = open("F:\D\OneDrive\Python\Spyder\test\", "rb")
^
SyntaxError: EOL while scanning string literal
If I change the line to -
attachment = open("F:\\D\\OneDrive\\Python\\Spyder\\test\\", "rb")
I get -
attachment = open("F:\\D\\OneDrive\\Python\\Spyder\\test\\", "rb")
FileNotFoundError: [Errno 2] No such file or directory:
'F:\\D\\OneDrive\\Python\\Spyder\\test\\'
If you work in Windows you must use windows path format. Method open with 'rb' parameters read file in byte mode if file is exist. You try read the directory!?
attachment = open('F:\\D\\OneDrive\\Python\\Spyder\\test\\myfile.txt", "rb")
equal
attachment = open(r'F:\D\OneDrive\Python\Spyder\test\myfile.txt', 'rb')
This represents the path correctly, but fails to provide a file name, because the trailing \ means a directory.
attachment = open("F:\\D\\OneDrive\\Python\\Spyder\\test\\myfile.txt", "rb")
What you likely want is
# Note the r and the lack of a trailing slash.
attachment = open(r"F:\D\OneDrive\Python\Spyder\test\myfile.txt", "rb")
I have found different code here and this works. Still can't work out why the original code does not work -
python program to rename the file with current date in MMDDYYY format and send email with attachment
Fixed code -
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "username#gmail.com"
toaddr = "username2#gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Please find the attachment"
body = "HI"
msg.attach(MIMEText(body, 'plain'))
filename = "myfile.txt"
#dt = str(datetime.datetime.now())
attachment = open("F:\\D\\OneDrive\\Python\\Spyder\\myfile.txt", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

Resources