I'd like to delete email from specific sender with python.
Here is my codes to delete all emails from my email account.
Question 1) How can I delete specific emails from specific sender? (ex: anyspamsender#gmail.com)
Question 2) How can I delete specific emails of which email title contains specific text ? (title : Delivery Status Notification (Failure))
import imaplib
box = imaplib.IMAP4_SSL('imap.gmail.com', 993)
box.login("emailid","password")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()
I got it
typ, data = box.search(None, 'from','mailer-daemon#googlemail.com')
Related
I am attempting to create a simple script to check my Gmail for emails with a certain title. When I run this program on Python 3.7.3 I receive this data: ('OK', [b'17']).
I need to access the body of the email within python. I am just not sure what to do with the data that I have.
Here is my current code:
import imaplib
import credentials
imap_ssl_host = 'imap.gmail.com'
imap_ssl_port = 993
username = credentials.email
password = credentials.passwd
server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
server.login(username, password)
server.select('INBOX')
data = server.uid('search',None, '(SUBJECT "MY QUERY HERE!")')
print(data)
The result from running the code:
('OK', [b'17'])
I know it is a little rough, but I am still learning, so any advice you have to help me improve would be greatly appreciated!
You need to first list the contents of the selected mailbox and fetch one of the items. You could do something like this (also check the link suggested by #asynts)
imap.select('Inbox')
status, data = imap.search(None, 'ALL')
for num in data[0].split():
status, data = imap.fetch(num, '(RFC822)')
email_msg = data[0][1]
If you only want specific fields in the body, instead of parsing the RFC you could filter fields like:
status, data = imap.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT DATE FROM TO)])')
Intro
I'd like to create some sort of archiving script, which would collect all Outlook (unicode) emails's date, sender (name+address), recipient(s) (name(s)+address(es)), subject and put them in a CSV file.
(The extra super solution would be if it could extract the containing folders' name and possible categories as well - although it is not a must.
And as final step, I would like to make it portable, so others could use it without having Python.)
(I'm using Python 2.7 and Outlook 2013)
Code
Here's what I have so far:
import win32com.client
import sys
import unicodecsv as csv
output_file = open('./outlook_farming_001.csv','wb')
output_writer = csv.writer(output_file, delimiter = ";", encoding='latin2')
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox.
messages = inbox.Items
for i, message in enumerate(messages): # enumerated the items
try:
sender = message.SenderName
sender_address = message.sender.address
sent_to = message.To
date = message.LastModificationTime
subject = message.subject
output_writer.writerow([
date,
sender,
sender_address,
sent_to,
subject])
except Exception as e:
()
output_file.close()
The questions:
How to make sure it extracts all the email? (When I run the script, it works, but it extracted only 1555 emails, although my Outlook Inbox sais, it contains 4785.)
How to make it work on all the Outlook folders? (It only deals with Inbox, but I would need all the other folders (sent, and other created ones))
How to get the recipients' email address? (I can only extract the screened names)
If you have any tip for any of the questions, that would be greatly appreciated.
Thanks in advance!!
For question 2:
inbox = outlook.GetDefaultFolder(6)
"6" in the code refers to Inbox.
for folder in outlook.Folders:
print(folder.Name)
use the above for loop to look for all the folders in your mailbox.
For question 3:
To get sender email ID, you can use this piece of code:
messages = inbox.Items
message = messages.GetFirst()
sender_emailid =message.SenderEmailAddress
For question 1:
I dont have an answer. Sorry
I am trying to use python to go through outlook and get all emails by a sender. I have looked but can't find out how to do this. I can get an email by subject and return the sender, but I am looking to get all senders and then return the subject? This is what I am using to get sender by subject.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages("Test 08/18/14")
print(message.sender)
This returns the sender for the mail with the subject "Test 08/19/14"
I would like to go through my email and get all email subjects from a certain sender.
It looks like you're looking for the SenderEmailAddress property.
You could go through your messages for a particular sender via:
for m in messages:
if m.SenderEmailAddress == 'some_sender#somewhere.com':
print(m)
Ok, I am working on a type of system so that I can start operations on my computer with sms messages. I can get it to send the initial message:
import smtplib
fromAdd = 'GmailFrom'
toAdd = 'SMSTo'
msg = 'Options \nH - Help \nT - Terminal'
username = 'GMail'
password = 'Pass'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username , password)
server.sendmail(fromAdd , toAdd , msg)
server.quit()
I just need to know how to wait for the reply or pull the reply from Gmail itself, then store it in a variable for later functions.
Instead of SMTP which is used for sending emails, you should use either POP3 or IMAP (the latter is preferable).
Example of using SMTP (the code is not mine, see the url below for more info):
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername#gmail.com', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
Shamelessly stolen from here
Uku's answer looks reasonable. However, as a pragmatist, I'm going to answer a question you didn't ask, and suggest a nicer IMAP and SMTP library.
I haven't used these myself in anything other then side projects so you'll need to do your own evaluation, but both are much nicer to use.
IMAP
https://github.com/martinrusev/imbox
SMTP:
http://tomekwojcik.github.io/envelopes/
I can suggest you to use this new lib https://github.com/charlierguo/gmail
A Pythonic interface to Google's GMail, with all the tools you'll
need. Search, read and send multipart emails, archive, mark as
read/unread, delete emails, and manage labels.
Usage
from gmail import Gmail
g = Gmail()
g.login(username, password)
#get all emails
mails = g.inbox().mail()
# or if you just want your unread mails
mails = g.inbox().mail(unread=True, from="youradress#gmail.com")
g.logout()
import sys, imaplib
from email.parser import HeaderParser
mail = imaplib.IMAP4_SSL(SERVER, PORT)
status, data = mail.search(None, 'ALL')
for msg_id in data[0].split():
status, message = mail.fetch(msg_id, '(RFC822)')
print message[0][1]
mail.close()
mail.logout()
I am trying to fetch emails from gmail via imap. All works fine, except that I am not able to extract header (subject, sender, date) from the message. In the above code, message[0][1] contains my email.
The only way I am able to get the header is to ask the imap server again, specifically for header:
status, message = mail.fetch(msg_id, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
parser = HeaderParser()
header = parser.parsestr(message[0][1])
print header
could somebody please advise how to do it?
I assume you've got the full email, not only the message body.
raw_message = """From: Santa Claus <santa#aintreal.no>
To: Some Dude <some#du.de>
Subject: I have lost your presents.
Dude, i am so sorry.
"""
import email
msg = email.message_from_string(raw_message)
print(msg['Subject']) # "I have lost your presents."
msg is a email.message.Message object.