Python Outlook Sent Folder - python

I created an automated email sender in Python for Outlook. It works fine, but I was wondering if it is possible to save the emails it sends in the sent folder. I'm sure there is, but I am unsure where to begin. Any help would be appreciated.
This is in Python 3.6
======
from tkinter import *
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import csv
import time
import warnings
root = Tk()
root.geometry('200x200')
email_label = Label(root, text="Enter your email")
email_label.pack()
username = Entry(root, width = 30)
username.pack()
password_label = Label(root, text="Enter your password")
password_label.pack()
password = Entry(root, show="*", width = 30)
password.pack()
def add_var():
user_name = username.get()
pass_word = password.get()
with open("emailtk.csv") as f:
try:
reader = csv.reader(f)
for row in reader:
time.sleep(3)
address = row[0]
first_name = row[1]
last_name = row[2]
name = first_name+' '+last_name
company = row[4]
msg = MIMEMultipart()
msg["To"] = address
msg["From"] = user_name
msg["Subject"] = subject
print("Will now send an email to %s at %s at %s" % (name, company, address))
msgText = MIMEText("""
Hello %s!
""" % (name), 'html')
msg.attach(msgText) # Added, and edited the previous line
time.sleep(5)
smtp = smtplib.SMTP('Outlook.com', 25)
smtp.ehlo()
smtp.starttls()
smtp.login(user_name,pass_word)
smtp.sendmail(user_name, address, msg.as_string())
print("email sent")
print("======================")
print()
smtp.quit()

Sending via SMTP will not copy the messages into the Sent Items folder. You will need to use Outlook Object Model (via win32com) or EWS (in case of Exchange Server).
UPDATE: as of Summer 2019, messages sent through Office 365 SMTP servers are saved in the Sent Items folder of the sending account mailbox.

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

Room Temperature Alarm to Email - Raspberry Pi

I'm trying to send and email based on High temperature or humidity but i cant figure out how to add this. Its my first time using DHT22 with Raspberry Pi so not sure how to structure my code.
I've tried a variety of codes others have suggested but they either no longer work on Python 3 (originally Python 2 - depreciated), or the code I've written just doesn't do anything except monitor and log with no email on high temp.
My original coding so far is this:
import os
import time
from time import sleep
from datetime import datetime
import Adafruit_DHT
file = open("/home/pi/TempHumLog.csv", "a")
if os.stat("/home/pi/TempHumLog.csv").st_size == 0:
file.write("Date,Time,Temperature,Humidity\n")
while True:
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
temperature, humidity = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
file.write("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
file.flush()
print("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
time.sleep(5)
import smtplib
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'example#gmail.com' #change this to match your gmail account
GMAIL_PASSWORD = 'example pw' #change this to match your gmail password
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
"MIME-Version: 1.0", "Content-Type: text/html"]
headers = "\r\n".join(headers)
#Connect to Gmail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
#Send Email & Exit
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
session.quit
sender = Emailer()
while True:
if temperature > 24:
sendTo = 'example#gmail.com'
emailSubject = "High Temp!"
emailContent = "<br>A High Temp has Activated At: " + time.ctime() + "<br><br>Check The Room Temperature Levels"
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
elif temperature < 23:
sendTo = 'example#gmail.com'
emailSubject = "Room Temp Healthy"
emailContent = "High Room Temp Alarm Has Cleared At: " + time.ctime()
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
time.sleep(5)
At this time, no errors come through the terminal but it doesn't send any email. I've tried adding something like this:
instance = dht22.DHT22(pin=4)
while True:
result = instance.read()
tempHI = 26
tempLOW = 19
if (result.temperature) > tempHI:
**Send Email Script**
But no luck!
Any ideas how i can get the high temperature to trigger the email?

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)

i got a problem when while sending emails from python , some emails get received but for a specific emails it wont it show the following error

the error is :'utf8' is an invalid keyword argument for Compat32
im trying to get Excel sheet that content emails and send emails to them from my gmail account the problem is most of the emails send successfully but when it reach a specific email it shows that error, btw im using tkinter as GUI
the email content is (email body uploaded by .txt, pdf file, the Excel sheet that i mentioned before)
def main():
global frame4
frame2.place_forget()
frame4 = Frame(root,borderwidth=5, relief=RIDGE)
frame4.place(x=0,y=160,width=400,height = 290)
frame3 = Frame(frame4,borderwidth=1)
frame3.place(x=0,y=0,width=390,height = 200)
Exit = Button(frame4, text="Exit",bd = 3, command=ask_quit)
Exit.place(x=300, y=240, width=80, height=30)
def go():
frame4.destroy()
getall()
Back = Button(frame4, text="Back",bd = 3, command=go)
Back.place(x=20, y=240, width=80, height=30)
list = Listbox(frame3, height=50, width=60)
scroll = Scrollbar(frame3, command=list.yview)
list.configure(yscrollcommand=scroll.set)
list.pack(side=LEFT)
list.update()
scroll.pack(side=RIGHT, fill=Y)
progress = ttk.Progressbar(frame4, orient=HORIZONTAL, length=380, mode='determinate')
progress.place(x= 10, y= 205,width =370,height =13)
emails = get_contacts() # read contacts
r = len(emails)
def check():
if r == 0:
messagebox.showerror("Error", "No email were found, Upload another Excel file")
frame4.place_forget()
getall()
else:
return
check()
message_template = read_template(text_path)
MY_ADDRESS = email2.get()
PASSWORD = password.get()
subject = subject1.get()
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(MY_ADDRESS, PASSWORD)
g = 0
progress['maximum'] = 100
for email in emails:
msg = MIMEMultipart() # create a message
message = message_template
msg['From'] = MY_ADDRESS
msg['To'] = email
msg['Subject'] = subject
filename = pdf_path
fo = open(filename, "rb")
attach = MIMEApplication(fo.read(), _subtype="ppt")
encoders.encode_base64(attach)
fo.close()
lastnamepath = os.path.basename(os.path.normpath(filename))
attach.add_header('Content-Disposition', 'attachment', filename=lastnamepath)
msg.attach(MIMEText(message,'plain'))
msg.attach(attach)
list.insert(END, email)
list.update()
g+=(100/r)
progress['value'] = g
frame4.update_idletasks()
time.sleep(0.5)
s.send_message(msg)
#s.sendmail(MY_ADDRESS,msg)
if progress['value'] == 100:
done = Label(frame4, text= "Done")
done.place(x=300, y=220, width=80, height=20)
del msg
s.close()
Thanks every body for helping me , i already find the problem, the main problem was some of the email show with (\xa0) in front of some emails so the solution:
email = unidecode.unidecode(email)

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.

Categories

Resources