printing a list inside a triple quote - python

I would like to print elements of a list inside an email message.
I defined my list in my python script like:
exceptions = []
At the end of the script the list will have the following elements:
This is a boy.
This is a girl.
This is a dog.
I would like to print the elements of the list called 'exceptions' inside an email that is contrived in the python script.
fromaddr = 'xxx#xxx.com'
toaddrs = 'xxx#xxx.com'
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
!!!PRINT THE EXCEPTION LIST HERE!!!
"""
print "Message length is " + repr(len(msg))
smtp_server = 'xxxxx.com'
smtp_username = 'xxxxxx'
smtp_password = 'xxxxxx'
smtp_port = '587'
smtp_do_tls = True
server = smtplib.SMTP(
host = smtp_server,
port = smtp_port,
timeout = 10
)
server.starttls()
server.ehlo()
server.login(smtp_username, smtp_password)
server.sendmail(fromaddr, toaddrs, msg)
print server.quit()
Any help will be greatly appreciated.

i would prefer MIMEText
import smtplib
from email.mime.multipart import MIMEText
msg = MIMEText("your_maeeage")
msg['From'] = <sender-email>
msg['To'] = <reciver-email>
msg['Subject'] = "your_subject"
server = smtplib.SMTP(<server>,<port>)
server.starttls()
server.login(Username,password)
server.sendmail(from_addr,to_addr,msg.as_string())

Format is a nice method to know which allows you to put place holders in a list. Of course, here you could simple append to the list, but it's useful. Use join to format the list of strings into a single string, here separated by a new line (\n).
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
{}
""".format('\n'.join(exceptions))
or:
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
""" + '\n'.join(exceptions)

Related

How to tell program to sleep for 60 seconds after 50 actions have been completed (emails sent) in python

I have this code that sends out emails individually through gmail from a list of emails in an excel file. I just want to know how to make the bot pause for 60 seconds after it's sent 50 emails and then continue with the list after the 60 seconds is up. I'm just trying to be safe with gmails daily limits.
import smtplib
import openpyxl as xl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = str(input('Your Username:' ))
password = str(input('Your Password:' ))
From = username
Subject = 'Free Beats and Samples For You :)'
wb = xl.load_workbook(r'C:\Users\19548\Documents\EMAILS.xlsx')
sheet1 = wb.get_sheet_by_name('EMAIL TEST - Sheet1')
names = []
emails = []
for cell in sheet1['A']:
emails.append(cell.value)
for cell in sheet1['B']:
names.append(cell.value)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username, password)
for i in range(len(emails)):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = emails[i]
msg['Subject'] = Subject
text = '''
{}
'''.format(names[i])
msg.attach(MIMEText(text, 'plain'))
message = msg.as_string()
server.sendmail(username, emails[i], message)
print('Mail sent to', emails[i])
server.quit()
print('All emails sent successfully!')
You can use time.sleep() to wait a given number of seconds, and you can keep track of the number of emails sent using a variable that gets incremented with each iteration of the loop. Since you're already working with both the emails themselves and their indices, you can simplify this counting by using Python's enumerate function, which gives you both the next value and its corresponding index:
for index, email in enumerate(emails, start=1):
msg = <...>
message = msg.as_string()
server.sendmail(username, email, message)
if index % 50 == 0:
time.sleep(60)
if(your_value%50==0):
time.sleep(60)

Python MIME email attachment sending method sends jpg files as "noname.eml" instead

When I use MIME and SMTPLIB instead of sending my attachment "random.jpg" it sends "noname.eml" which is unopenable and unseeable, I am unable to send attachments correctly for this reason. Why is this caused and how can I solve it?
I tried to change the extension from "png" to "jpg" but the issue pursues.
fromaddr1 = ""
toaddr1 = ""
accpass1 = ""
msg1 = MIMEMultipart()
msg1['From'] = fromaddr1
msg1['To'] = toaddr1
msg1['Subject'] = "YOUR COMPUTER HAS BEEN ACCESSED"
body1 = "Someone has gained access to your computer"
msg1.attach(MIMEText(body1, 'plain'))
filename1 = "random.jpg"
attachment1 = open("random.jpg","rb")
part1 = MIMEBase('application', 'octet-stream')
part1.set_payload((attachment1).read())
encoders.encode_base64(part1)
part1.add_header('Content-Disposition', "attachment1; filename1= %s" %
filename1)
msg1.attach(part1)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr1, accpass1)
text = msg1.as_string()
server.sendmail(fromaddr1, toaddr1, text)
server.quit()
in header:
from email.mime.application import MIMEApplication
instead attachment:
with open(PATH_TO_ZIP_FILE,'rb') as file: msg.attach(MIMEApplication(file.read(), Name='filename.zip'))

Send e-mail from Python through Zoho

I'm trying to send an e-mail from Zoho, but: sometimes I receive emails, sometimes not, and it happens also with other persons.
But in mail.zoho.com all emails exists in SENT E-MAILS, but people sometimes did not receive, and it is not a Spam problem.
def sendMailTo(subject='', msgHTML='', to='', no_reply=False, mail_type=None):
try:
j = json.loads(msgHTML)
msgHTML = ""
for k in j.keys():
msgHTML += str(k) + ": " + str(j[k])
msgHTML += "\n"
except ValueError:
pass
#Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg2 = MIMEText(msgHTML, 'html', 'UTF-8') #Content-Type: text/html; charset="us-ascii"
msg.attach(msg2)
# This example assumes the image is in the current directory
import os
os.chdir(os.path.dirname(__file__))
#print(os.getcwd())
fp = open('./utils/images/logo.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<logo>')
msg.attach(msgImage)
fp = open('./utils/images/facebook.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<facebook>')
msg.attach(msgImage)
recipients = [to]
TO = ", ".join(recipients)
msg['Subject'] = subject
msg['To'] = TO
if no_reply:
FROM = "no-reply#xxxxx.com"
msg['From'] = FROM
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP_SSL('smtp.zoho.com', 465)
# s.set_debuglevel(1)
# s.starttls()
s.ehlo()
s.login(FROM, 'yoyoyoyoyoyo')
s.sendmail(FROM, recipients, msg.as_string())
s.quit()
else:
FROM = "xxxxxxxxx#gmail.com"
msg['From'] = FROM
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.gmail.com', 587)
#s.set_debuglevel(1)
#s.ehlo()
s.starttls()
s.login(FROM, 'yoyoyoyoyoyo')
s.sendmail(FROM, recipients, msg.as_string())
s.quit()

sending emails in a loop In PYTHON 2.7

I am currently trying to make a program that send multiple emails to my self in a loop. I have already written 2 patches of code but i can not seem to get them to work. (I am running this on a raspberry pi so exsuse any weird directorys).
This is my first patch of while loop code
import os
i = 0
while i < 2:
os.pause(4)
os.system("home/Tyler/desktop/test.py")
i += 1
This opens the email "sending" part /\ .
This down here is the "sending" part /
import smtplib
smtpUser = 'smilingexample#gmail.com'
smtpPass = 'password'
toAdd = 'Example#aim.com'
fromAdd = smtpUser
subject = 'yep'
header = 'to: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'hi'
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)
s.quit ()
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email import Charset
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
maillist = []
def send_email(messages_list, smtpUser=None, smtpPass=None, tls=False):
failed = []
try:
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
if tls:
s.starttls()
s.ehlo()
if smtpUser and smtpPass:
s.login(smtpUser, smtpPass)
except:
print "ehlo failed"
failed = [x[0] for x in messages_list]
else:
for to_address,from_address,subject,encoding,mesg in messages_list:
try:
if len(mesg) == 2:
msg = MIMEMultipart('alternative')
else:
msg = MIMEText(mesg[0],'plain','utf-8')
msg['Subject'] = "%s" % Header(subject, 'utf-8')
if len(from_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[-1])
else:
msg['From'] = from_address[-1]
if len(to_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(to_address[0], 'utf-8'), to_address[-1])
else:
msg['To'] = to_address[-1]
msg.set_charset("utf-8")
if len(mesg) == 2:
part1 = MIMEText(mesg[0], 'plain','utf-8')
part2 = MIMEText(mesg[1], 'html','utf-8')
msg.attach(part1)
msg.attach(part2)
s.sendmail(from_address[-1], to_address[-1], msg.as_string())
except:
traceback.print_exc()
failed.append(to_address[-1])
try:
s.quit()
except:
pass
return failed
maillist.append(( ['someone#gmail.com'],["Me","noreply#example.com"],'Subject','utf-8',['text_message','html but you can delete this list element'] ))
for k in send_email(maillist, smtpUser='you#gmail.com', smtpPass='pwd', tls=True):
print k, 'not delivered'
Here's what we use to send alternative Mime messages with alternative body. It is not necessary though so you can send simple text messages as well.
It's prepared to send from localhost but you can easily modify it to use it properly.

python emailing one line at a time

My email program is emailing each line of the message as a separate email, i would like to know how to send all of the message in one email, when the email is sent the program will return to the beginning.
import smtplib
from email.mime.text import MIMEText
a = 1
while a == 1:
print " "
To = raw_input("To: ")
subject = raw_input("subject: ")
input_list = []
print "message: "
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
msg['Subject'] = subject
msg['From'] = '123#example.com'
msg['To'] = To
server = smtplib.SMTP_SSL('server', 465)
server.ehlo()
server.set_debuglevel(1)
server.ehlo()
server.login('username', 'password')
# Send a properly formatted MIME message, rather than a raw string
server.sendmail('user#example.net', To, msg.as_string())
server.close()
(the part that takes multiple lines was made with the help Paul Griffiths, Multiline user input python)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
You are calling server.sendmail in this loop.
Build your entire msg first (in a loop), THEN add all of your headers and send your message.

Categories

Resources