Email alert if file doesn't exist - Python - python

I'm very new to python.
I have a folder called "etc" with a filename password.txt when generates every night. I would like to run a python script in windows task on daily basis to check if password.txt doesn't exist then send email to abc#ouremail.co.uk else do not send any email.
I want to trigger email based on the below condition. When the condition is "false" send email else no action taken. How can I achieve it, any help on this would be greatly appreciated.
os.path.isfile("/etc/password.txt")
True
Kind regards,
Biswa

Check if File Exists using the os.path Module
The os.path module provides some useful functions for working with pathnames. The module is available for both Python 2 and 3
import os.path
if os.path.isfile('filename.txt'):
print ("File exist")
else:
print ("File not exist")
Then to send an email you can use smtplib (one topic here)
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = 'me#gmail.com'
msg['To'] = 'you#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me#gmail.com', 'mypassword')
mailserver.sendmail('me#gmail.com','you#gmail.com',msg.as_string())
mailserver.quit()

Related

How to automatically send personalized emails with a pdf attachment in Python?

I am a beginner programmer and I am trying to write a program that automatically sends personalized emails to a list of receivers in a csv file with a pdf attachment.
My current code sends personalized emails but I don't know how to add an attachment. Also, I think it's best practice to write the program in a function but I don't know how to do that either.
It would be greatly appreciated if anyone could help me out. Also, I want to keep it as simple as possible so that I still understand what every line of code does.
import os
import smtplib, ssl
import csv
# Sender credentials (from environment variables)
email_address = os.environ.get("email_user")
email_pass = os.environ.get("email_app_pass")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(email_address, email_pass) # Log into sender email account
# Email information
subject = "Testing Python Automation"
body = """ Hi {name},\n\n This email was entirely generated in Python. So cool!
"""
msg = f"Subject: {subject}\n\n{body}"
with open("contacts_test.csv") as file:
reader = csv.reader(file)
next(reader) # Skip header row
for name, email in reader:
server.sendmail(email_address, email, msg.format(name=name))
file.close()
server.quit()
This will only work using gmail and make sure you have manually set up
special permissions on your gmail account for the program to be able to send email on behalf of you. The process is described here.
You can use other email address services for that you need to change the smtp server address and the smtp port number in line 32 accordingly and take care of any other additional steps required.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
body = """
Hi {name},\n\n This email was entirely generated in Python. So cool!
""".format(name="Name")
# details
sender = 'example1#gmail.com' # my email
password = '&*password.$' # my email's password
receiver = 'example2#gmail.com' # receiver's email
msg = MIMEMultipart()
msg['To'] = receiver
msg['From'] = sender
msg['Subject'] = 'Testing Python Automation'
msg.attach(MIMEText(body, 'plain'))
pdfname = "mypdf.pdf" # pdf file name
binary_pdf = open(pdfname, 'rb')
payload = MIMEBase('application', 'octate-stream', Name=pdfname)
payload.set_payload((binary_pdf).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=pdfname)
msg.attach(payload)
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, password)
text = msg.as_string()
session.sendmail(sender, receiver, text)
session.quit()
print('[#] Mail Sent!')

How do I input text into a Python script on a remote server?

I have a python script saved on an Amazon EC2 instance that sends an email:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "filleremail#gmail.com"
my_password = r"password"
you = "receiver#gmail.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
#TODO: How do I get email text from user
part2 = MIMEText(email_text)
msg.attach(part2)
# Send the message via gmail's regular server, over SSL - passwords are being sent, afterall
s = smtplib.SMTP_SSL('smtp.gmail.com')
# uncomment if interested in the actual smtp conversation
# s.set_debuglevel(1)
# do the smtp auth; sends ehlo if it hasn't been sent already
s.login(me, my_password)
s.sendmail(me, you, msg.as_string())
s.quit()
I want to submit text from a mobile app using a URL to fill the email_text variable. I have some experience with POST and GET requests but not on connecting them through Python. Can someone please point me in the right direction?

Python: attach .txt to an email

I did some google researches and found a lot of stuff. Unfortunately I do not understand what I found so I need to open a new "public request". As I told in my title already I want to attach a .txt file to my email. Sorry to ask that again after thousands of people already did this, but here is my method to send the mail:
import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import config
#creating file to write the keys in later
file = open("my_filename.txt", "w+")
#creating subject and message for the email
subject = "Test123 new / updated"
msg = "look in attachment"
def send_mail(subject, msg)
try:
server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login(config.EMAIL_ADDRESS, config.PASSWORD)
message = "Subject: {}\n\n{}".format(subject, msg)
server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_RECEIVER, message)
server.quit()
print("success: Email sent!")
except:
print("Email failed to send")
This worked fine for me (just managed it with some research too. To attach the file finally I found something like that:
msg = MIMEMultipart()
#some other code to create a mail with subject and stuff like that
msg.attach(MIMEText(text))
If I change "text" to "my_filename.txt" it do not work. What do I need to change?
ahh, I had an other own idea. I removed the line "msg = "look in attachment"" and instead of this I used the method file.read(). So my line where I send the mail looks like this now:
server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_RECEIVER, file.read())

Python 2.7 - I am Using smtplib to send mails to multiple people, but the subject line in email sent is not reflecting in every mail

I am using smtplib to send mails to multiple users, I am reading email ids from mail.txt , and names of receivers from names.txt file and subject from subject.txt file,
Somehow the subject is not reflecting in all emails, only last mail that is sent has subject and others don't. But when I print the subject in each iteration it prints, I am not sure why this is happening. I tried to change number of receipts and checked, but the issue doesn't solve. Also I tried to keep the import statements outside the loop as well.
Can you please help me with this code.
Code :
ob1 = open("names.txt","r")
fname = ob1.readlines()
ob1.close()
ob2 = open("mail.txt","r")
email = ob2.readlines()
ob2.close()
ob3 = open("subject.txt","r")
aname = ob3.readlines()
ob3.close()
for i in range(len(fname)):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = 'my_email_id'
msg['To'] = email[i]
msg['Subject'] = aname[i]
message = 'some mail text'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('my_email_id', '******')
mailserver.sendmail('my_email_id',email[i],msg.as_string())
mailserver.quit()

How to send Gmail email with multiple CC:'s

I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?
I've rustled up a bit of code for you that shows how to connect to an SMTP server, construct an email (with a couple of addresses in the Cc field), and send it. Hopefully the liberal application of comments will make it easy to understand.
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
## The SMTP server details
smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"
## The email details
from_address = "address1#domain.com"
to_address = "address2#domain.com"
cc_addresses = ["address3#domain.com", "address4#domain.com"]
msg_subject = "This is the subject of the email"
msg_body = """
This is some text for the email body.
"""
## Now we make the email
msg = MIMEText(msg_body) # Create a Message object with the body text
# Now add the headers
msg['Subject'] = msg_subject
msg['From'] = from_address
msg['To'] = to_address
msg['Cc'] = ', '.join(cc_addresses) # Comma separate multiple addresses
## Now we can connect to the server and send the email
s = SMTP_SSL(smtp_server, smtp_port) # Set up the connection to the SMTP server
try:
s.set_debuglevel(True) # It's nice to see what's going on
s.ehlo() # identify ourselves, prompting server for supported features
# If we can encrypt this session, do it
if s.has_extn('STARTTLS'):
s.starttls()
s.ehlo() # re-identify ourselves over TLS connection
s.login(smtp_username, smtp_password) # Login
# Send the email. Note we have to give sendmail() the message as a string
# rather than a message object, so we need to do msg.as_string()
s.sendmail(from_address, to_address, msg.as_string())
finally:
s.quit() # Close the connection
Here's the code above on pastie.org for easier reading
Regarding the specific question of multiple Cc addresses, as you can see in the code above, you need to use a comma separated string of email addresses, rather than a list.
If you want names as well as addresses you might as well use the email.utils.formataddr() function to help get them into the right format:
>>> from email.utils import formataddr
>>> addresses = [("John Doe", "john#domain.com"), ("Jane Doe", "jane#domain.com")]
>>> ', '.join([formataddr(address) for address in addresses])
'John Doe <john#domain.com>, Jane Doe <jane#domain.com>'
Hope this helps, let me know if you have any problems.
If you can use a library, I highly suggest http://libgmail.sourceforge.net/, I have used briefly in the past, and it is very easy to use. You must enable IMAP/POP3 in your gmail account in order to use this.
As for a code snippet (I haven't had a chance to try this, I will edit this if I can):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
#EDIT THE NEXT TWO LINES
gmail_user = "your_email#gmail.com"
gmail_pwd = "your_password"
def mail(to, subject, text, attach, cc):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
#THIS IS WHERE YOU PUT IN THE CC EMAILS
msg['Cc'] = cc
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
mail("some.person#some.address.com",
"Hello from python!",
"This is a email sent with python")
For the snippet I modified this

Categories