I want to create a script that sends an email if anything that my application is monitoring changes (for example, if a user's game score changes from 89 to 75). I want to place that script in the Scripts directory. It will be called as part of a daily update that happens for the site.
Here is the part of my code and where I want to place the email alert:
!/usr/bin/env python
import sys
from subprocess import call
from pymomgo import MongoClinet
from bson import ObjectId
from datetime import datetime
prog_list= ['network-to-ips.py',
'ips-to-scope.py',
'update-ip-scope-staus',
'gamer-profile-score.py']
if len(sys.argv) < 2:
raise SystemExit('usage: %s PROFILE-ID' % sys.argv[0])
profile_id = sys.argv[1]
print 'Begin Gamer-Profile-Update: %s : %s ' % (profile_id, dateime.now())
timestame = datetime.utcnow()
Client = MongoClient('mongodb://localhost:29812/')
db = client.gamer
db.porgile.update({'_id: BjectId9profile_id)},
{'$set': {'update_start': datetime.now(), 'status; : 'updating'}})
# Start Update
gstdout=open('/opt/log/gamer/profile-updates/%s.log' % (profile_id), 'w')
gstderr=open('/opt/log/gamer/profile-update%s-err.log' % (profile_id), 'w')
count=1
for prog in prog_lost:
call(['opt/gamer/scripts/%s' % prog, progile_id], stdout=gstout, stderr=gstderr)
count = count +1
progess= int((100/len(prog_list))*count)
print "Progess", progess
db.profile.update({'_id': ObjectID9profile_id)},
{'%set': {'update_progress': progress }})
db.profile.update({'_id': ObjectId(profile_id)},
{'%set': {'update_end': dateime.now(), 'status': 'idle', 'update_progress':0}})
print 'End Gamer-Profile-Update %s : %s ' % 9profile_id, dateime.now()
I want to place this in the Prog_list:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "YOUR ADDRESS"
toaddr = "ADDRESS YOU WANT TO SEND TO"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
Related
I have a working send email script which takes txt file and send it encoded.
i want to be able to design (html) this encoded txt in the email body.
i know how generally design a text in email body but i cant design the encoded txt in the html.
i want to combine the two scripts and be able to design the encoded text ( first script output) into the html design of the second script
first script send email ( Works but undesigned body ):
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mailing cofig:
ID = 'XX
PASSWORD = XX
email_reciever = XX
filename = r".\Reports\Report.txt"
def send_email(subject, msg):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(ID, PASSWORD)
message = 'Subject:{}\n\n{}'.format(subject, msg)
server.sendmail(ID, email_reciever, message)
# server.sendmail(ID, email_reciever, msg.as_string())
print('Succes')
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your BeeHero Report'
msg['From'] = ID
msg['To'] = email_reciever
with open(filename, "r") as filename:
text = ''.join(filename.readlines()[1:])
msg.set_payload(text.encode())
subject = "BeeHero Report"
send_email(subject, msg)
output:
https://imgur.com/a/g6m0WKt
Second script ( designed body but not encoded as the first output)
# Sending email script Amit
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mailing cofig:
ID = XX
PASSWORD = XX
email_reciever = XX
filename = r".\Reports\Report.txt"
def send_email(msg):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(ID, PASSWORD)
server.sendmail(ID, email_reciever, msg.as_string())
print('Succes')
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your BeeHero Report'
msg['From'] = ID
msg['To'] = email_reciever
with open(filename, "r") as filename:
text = ''.join(filename.readlines()[1:])
html = (f"""
<!DOCTYPE html>
<html>
<body>
<h1 style="color:SlateGray;">{text}</h1>
</body>
</html>
""")
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
send_email(msg)
output:
https://imgur.com/a/5wqUoSa
I have the following code where the Cc email list is not working meaning emails are not received to the folks/groups in Cc list,email to To list is working,I just can't figure out what is wrong?any guidance on how to debug and fix it?
import time,smtplib
import pprint,logging,os,time,json
from subprocess import Popen, PIPE, call
from pprint import pprint
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
email = 'username2#company.com'
gerriturl = ""
def sendEmail2(type,data):
global originalchange
global gerriturl,email,username1
body = '''%s''' % (data)
#msg = MIMEMultipart(body)
msg = MIMEMultipart()
sender = 'techci#company.com'
receivers = []
cc = ['username1#company.com']
REPLY_TO_ADDRESS = 'embedded-tech-integrators#group.company.com'
if type =='failure':
print("Inside failure email %s"%email)
b = '\U0001F6A8'
print("b.decode('unicode-escape')")
receivers.append('username2#company.com')
#receivers.append(email)
print('%s'%receivers)
msg['Subject'] = '%s AUTO FAILED FOR GERRIT %s :PLEASE TAKE IMMEDIATE ACTION!!!'%(b.decode('unicode-escape'),gerriturl)
msg['From'] = sender
msg['To'] = ', '.join(receivers)
msg['Cc'] = ', '.join(cc)
msg["Content-Type"] = "text/html"
try:
mail = smtplib.SMTP('relay.company.com', 25)
msg.attach(MIMEText(body, 'html'))
msg.add_header('reply-to', REPLY_TO_ADDRESS)
print('Email sent successfully %s %s'%(receivers,cc))
except Exception as e:
logger.error('Problem sending email')
logger.error('%s' % e)
def main():
data = "THIS IS A TEST EMAIL"
sendEmail2('failure',data)
if __name__ == "__main__":
main()
The important thing is to pass the complete list of recipient email addresses to the sendmail() method - you need to concatenate the email addresses for the To, CC and BCC fields into a single list, not a string.
import smtplib
def send_email(subject, body_text, emails_to, emails_cc=[], emails_bcc=[]):
# Configuration
host = "localhost"
port = 1025
from_addr = "nobody#somewhere.com"
# Build the email body
body = "\r\n".join([
"From: %s" % from_addr,
"To: %s" % ', '.join(emails_to),
"CC: %s" % ', '.join(emails_cc),
"Subject: %s" % subject ,
"",
body_text
])
# Prepare the complete list of recipient emails for the message envelope
emails = emails_to + emails_cc + emails_bcc
# Connect to the server
server = smtplib.SMTP(host, port)
# Send the email
server.sendmail(from_addr, emails, body)
# Close the server connection
server.quit()
I'm working on a project of making my own Instant-Messaging program, even without graphics or anything, just to get to know the built-in modules in python.
Here, I tried to write a code that the user will input the username and password the user wants, and then a e-mail will be sent (to the user), that will contain a 12-character random string, and the user will input it back to the program. Somehow, when I run the code my whole computer freezes!
Here's the code:
import smtplib
SMTPServer = smtplib.SMTP("smtp.gmail.com",587)
SMTPServer.starttls()
SMTPServer.login(USERNAME, PASSWORD)*
userEmail = raw_input("Please enter your e-mail: ")
if verifyEmail(userEmail) == False:
while True:
userEmail = raw_input("Error! Please enter your e-mail: ")
if verifyEmail(userEmail) == True:
break
randomString = generateRandomString()
message = """From: From Person <%s>
To: To Person <%s>
Subject: Ido's IM Program Registration
Your registration code is: %s
""" %(SERVEREMAIL, userEmail, randomString)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(SERVEREMAIL, userEmail, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
inputString = raw_input("Input generated code sent: ")
This is a working example of a smtp client.
where does your code block?
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
class SMTPClient(object):
def __init__(self, recepient, subject, body):
self.recepient = recepient
self.subject = subject
self.body = body
self.mail_host = conf.get('smtp_server.host')
self.mail_port = conf.get('smtp_server.port')
self.username = conf.get('account.username')
self.password = conf.get('account.password')
self.mail_sender = conf.get('account.from')
self._setup()
def _setup(self):
self.smtp_client = smtplib.SMTP(self.mail_host, self.mail_port)
self.smtp_client.ehlo_or_helo_if_needed()
self.smtp_client.starttls()
self.smtp_client.login(self.username, self.password)
self._send_mail()
def _make_mail(self):
message = MIMEText(self.body, _charset='utf-8')
message['From'] = self.mail_sender
message['To'] = self.recepient
message['Subject'] = self.subject
return message.as_string()
def send_mail(self):
self.smtp_client.sendmail(self.mail_sender, self.recepient, self._make_mail())
self.smtp_client.quit()
This works for me!
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
gmail_user = 'example#hotmail.com'
gmail_pwd = 'somepassword'
subject = 'HEY'
text = 'Some text here'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = gmail_user
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
Encoders.encode_base64(part)
mailServer = smtplib.SMTP("smtp.live.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user,gmail_user, msg.as_string())
mailServer.close()
Problem: when i send mail to user then from user name not seen in to user inbox only show email-id but i need user name of sender
from: demo#gmail.com username: Demo
To: demotest#gmail.com
CODE
import smtplib
fromaddr = From
toaddrs = To
msg = 'Why,Oh why!'
username = From
password = *******
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
smtplib does not include automatically any header, and you need to include a From: header, so you have to put one by yourself doing something like:
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
As you can se in the DOCS.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = 'demo#gmail.com'
toaddrs = 'demotest#gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "good morning" #like name
msg['To'] = "GGGGGG"
body = MIMEText("example email body")
msg.attach(body)
username = 'demo#gmail.com'
password = ''
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
You just need to create the message correctly. I think the most convenient way to do it is using a special object for message. I placed a class which perhaps may help you to send messages in your project.
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
class EmailSender(object):
def __init__(self, subject, to, config):
self.__subject = subject
self.__to = tuple(to) if hasattr(to, '__iter__') else (to,)
self.__from = config['user']
self.__password = config['password']
self.__server = config['server']
self.__port = config['port']
self.__message = MIMEMultipart()
self.__message['Subject'] = self.__subject
self.__message['From'] = self.__from
self.__message['To'] = ', '.join(self.__to)
def add_text(self, text):
self.__message.attach(
MIMEText(text)
)
def add_image(self, img_path, name=None):
if name is None:
name = os.path.basename(img_path)
with open(img_path, 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name=name)
self.__message.attach(image)
def send(self):
server = smtplib.SMTP_SSL(self.__server, self.__port)
server.login(self.__from, self.__password)
server.sendmail(self.__from, self.__to, self.__message.as_string())
server.close()
sender = EmailSender("My letter", "my_target#email", {
'user': "from#email",
'password': "123456",
'server': "mail.google.com"
'port': 465
})
sender.add_text("Why,Oh why!")
sender.send()
Or go the easy way, by install yagmail and
Given:
To = 'someone#gmail.com'
From = 'me#gmail.com'
pwd = '******'
alias = 'someone'
Run:
import yagmail
yag = yagmail.SMTP(From, pwd)
yag.send({To: alias}, 'subject', 'Why,Oh why!')
Install might be done by pip install yagmail
I've been working on this for 2 days now and managed to get this script with a pcapng file attached to send but I cannot seem to make the message body appear in the email.
import smtplib
import base64
import ConfigParser
#from email.MIMEapplication import MIMEApplication
#from email.MIMEmultipart import MIMEMultipart
#from email.MIMEtext import MIMEText
#from email.utils import COMMASPACE, formatdate
Config = ConfigParser.ConfigParser()
Config.read('mailsend.ini')
filename = "test.pcapng"
fo = open(filename, "rb")
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent) # base 64
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
# Define the main headers
header = """ From: From Person <notareal#email.com>
To: To Person <someother#fakeemail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define message action
message_action = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body, marker)
# Define the attachment section
message_attachment = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" % (filename, filename, encoded_content, marker)
message = header + message_action + message_attachment
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
My goal is to ultimately have this script send an email after reading the parameters from a config file and attach a pcapng file along with some other text data describing the wireshark event. The email is not showing the body of the message when sent. The pcapng file is just a test file full of fake ips and subnets for now. Where have I gone wrong with the message body?
def mail_man():
if ms == 'Y' or ms == 'y' and ms_maxattach <= int(smtp.esmtp_features['size']):
fromaddr = [ms_from]
toaddr = [ms_sendto]
cc = [ms_cc]
bcc = [ms_bcc]
msg = MIMEMultipart()
body = "\nYou're captured event is attached. \nThis is an automated email generated by Dumpcap.py"
msg.attach("From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % ms_subject
+ "X-Priority = %s\r\n" % ms_importance
+ "\r\n"
+ "%s\r\n" % body
+ "%s\r\n" % ms_pm)
toaddrs = [toaddr] + cc + bcc
msg.attach(MIMEText(body, 'plain'))
filename = "dcdflts.cong"
attachment = open(filename, "rb")
if ms_attach == 'y' or ms_attach == "Y":
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(ms_smtp_server[ms_smtp_port])
server.starttls()
server.login(fromaddr, "YOURPASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
server.quit()
This is my second attempt, all "ms_..." variables are global through a larger program.
You shouldn't be reinventing the wheel. Use the mime modules Python has included in the standard library instead of trying to create the headers on your own. I haven't been able to test it out but check if this works:
import smtplib
import base64
import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
filename = "test.pcapng"
with open(filename, 'rb') as fo:
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent)
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
message = MIMEMultipart(
From=sender,
To=receiver,
Subject='Sending Attachment')
message.attach(MIMEText(body)) # body of the email
message.attach(MIMEApplication(
encoded_content,
Content_Disposition='attachment; filename="{0}"'.format(filename)) # b64 encoded file
)
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
I've left off a few parts (like the ConfigParser variables) and demonstrated only the email related portions.
References:
How to send email attachments with Python
Figured it out, with added ConfigParser. This is fully functional with a .ini file
import smtplib
####import sys#### duplicate
from email.parser import Parser
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import ConfigParser
def mail_man(cfg_file, event_file):
# Parse email configs from cfg file
Config = ConfigParser.ConfigParser()
Config.read(str(cfg_file))
mail_man_start = Config.get('DC_MS', 'ms')
security = Config.get('DC_MS', 'ms_security')
add_attachment = Config.get('DC_MS', 'ms_attach')
try:
if mail_man_start == "y" or mail_man_start == "Y":
fromaddr = Config.get("DC_MS", "ms_from")
addresses = [Config.get("DC_MS", "ms_sendto")] + [Config.get("DC_MS", "ms_cc")] + [Config.get("DC_MS", "ms_bcc")]
msg = MIMEMultipart() # creates multipart email
msg['Subject'] = Config.get('DC_MS', 'ms_subject') # sets up the header
msg['From'] = Config.get('DC_MS', 'ms_from')
msg['To'] = Config.get('DC_MS', 'ms_sendto')
msg['reply-to'] = Config.get('DC_MS', 'ms_replyto')
msg['X-Priority'] = Config.get('DC_MS', 'ms_importance')
msg['CC'] = Config.get('DC_MS', 'ms_cc')
msg['BCC'] = Config.get('DC_MS', 'ms_bcc')
msg['Return-Receipt-To'] = Config.get('DC_MS', 'ms_rrr')
msg.preamble = 'Event Notification'
message = '... use this to add a body to the email detailing event. dumpcap.py location??'
msg.attach(MIMEText(message)) # attaches body to email
# Adds attachment if ms_attach = Y/y
if add_attachment == "y" or add_attachment == "Y":
attachment = open(event_file, "rb")
# Encodes the attachment and adds it to the email
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename = %s" % event_file)
msg.attach(part)
else:
print "No attachment sent."
server = smtplib.SMTP(Config.get('DC_MS', 'ms_smtp_server'), Config.get('DC_MS', 'ms_smtp_port'))
server.ehlo()
server.starttls()
if security == "y" or security == "Y":
server.login(Config.get('DC_MS', 'ms_user'), Config.get('DC_MS', 'ms_password'))
text = msg.as_string()
max_size = Config.get('DC_MS', 'ms_maxattach')
msg_size = sys.getsizeof(msg)
if msg_size <= max_size:
server.sendmail(fromaddr, addresses, text)
else:
print "Your message exceeds maximum attachment size.\n Please Try again"
server.quit()
attachment.close()
else:
print "Mail_man not activated"
except:
print "Error! Something went wrong with Mail Man. Please try again."