Why email is not being send to CC list? - python

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()

Related

Sending emails with smtp python, problem with def block

I'm new to python, I'm working with python 3. I need to send an email with generated message. Everything is ok with message (I can print it) but somehow in that configuration, with that def-blocks emails aren't sent. What am I doing wrong? I don't get any error notifications.
import random
import string
import smtplib
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def randomMessage():
random_string1 = randomString()
random_string2 = randomString()
message = f"""\
Subject: {random_string1}
To: {receiver}
From: {sender}
{random_string2}"""
return message
def main():
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
message = randomMessage()
#print(message)
server.sendmail(sender, receiver, message)
if __name__ == '__main__':
main()
Problem was in message type. I changed it to MIMEText and it works now.
import random
import string
import smtplib
from email.mime.text import MIMEText
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
lettersDigits = string.ascii_lowercase + "0123456789"
return ''.join(random.choice(lettersDigits) for i in range(stringLength))
def makeMessage(subject, content):
message = MIMEText(content)
message["Subject"] = subject
message["From"] = sender
message["To"] = receiver
return message
def randomMessage():
return makeMessage(randomString(), randomString())
def sendMessage(message):
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())

How can I send email to multi addresses by smtplib?

I use bellow code I can send email to one account, but how can I send to multi account?
import smtplib
from email.mime.text import MIMEText
_user = "67676767#qq.com" #
_pwd = "orjxywulscbxsdwbaii" #
_to = linux213#126.com" #
msg = MIMEText("content") #
msg["Subject"] = "邮件主题测试" #
msg["From"] = _user
msg["To"] = _to
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(_user, _pwd)
s.sendmail(_user, _to, msg.as_string())
s.quit()
print ("Success!")
except smtplib.SMTPException as e:
print ("Falied,%s" % e)
Try this:
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.qq.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['k.ankur#abc.com', 'a.smith#abc.co.in']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

Send an email with SMTP in Python

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()

Python and Email Alerts

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()

Python SMTP/MIME Message body

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."

Categories