I want to save attachments from outlook using Python, Attachment from a fixed email subject. I already searched it got an answer that is not working and I cannot comment. - Save using Win32 Outlook
I tried the code and here it is -
from win32com.client import Dispatch
import datetime as date
import os
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()
sub_today = 'Download Attachment 1'
att_today = '1.csv'
for msg in all_inbox:
if msg.Subject == sub_today:
break
for att in msg.Attachments:
if att.FileName == att_today:
break
att.SaveAsFile(os.getcwd() + '\\1.csv')
att.ExtractFile('1.csv')
open(att)
att.WriteToFile('x')
Upon Executing it in Command Prompt I get error as -
D:\r>python attach.py
Traceback (most recent call last):
File "attach.py", line 21, in <module>
att.ExtractFile('1.csv')
File "C:\Program Files\Python37\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.ExtractFile
Attachment object in OOM (att variable in your code) does not expose the ExtractFile method. Neither does it expose the WriteToFile method.
Related
I'm currently trying calculate the leadtime of all outlook messages within a specific outlook folder using python. In general the script runs fine however, after roundabout 2000 emails I received the following error (part of code):
import win32com.client as win32
import pandas as pd
from datetime import date
import time
outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("example#example.com")
inbox = folder.Folders("Inbox")
messages = inbox.Items
df = pd.DataFrame()
index = 0
for msg in messages:
if (msg.SenderEmailType != "EX"):
print(str(msg.subject))
print('Begin date:', msg.SentOn.strftime('%Y-%m-%d'))
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
df.at[index, 'Subject'] = msg.subject
df.at[index, 'Begin date'] = msg.SentOn.strftime('%Y-%m-%d')
df.at[index, 'End date'] = msg.LastModificationTime.strftime('%Y-%m-%d')
I encounterd the following error:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\MailCounts.py", line 24, in <module>
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
I tried to debug it by selecting the specific email and put it into another outlook folder and then loop over it. But then it works fine without errors. So it seems to be folder specific?!
I have searched for several answers on the errors and the method in general. But as far as I can see, this answer was never asked before with a suitable answer.
Thanks in advance!
I am trying to send the coverage report generated after execution of test cases, which is generated in htmlcov folder,
import os
from django.conf import settings
from utils import email_utils
def pytest_sessionfinish(session, exitstatus):
to = ['xyz123#gmail.com']
body = 'test'
subject = 'coverage test'
attachment = 'htmlcov/index.html'
coverage_html = os.path.join(settings.BASE_DIR + '/' + attachment)
email_utils.send_email_with_attachment(to, body, subject, coverage_html,
'application/html',
'index.html')
while doing so I am getting the following error:
ERROR | 2020-03-12 10:07:57,180 | MainThread | email_utils.send_email_with_attachment.69 | a bytes-like object is required, not 'str'
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/mail/message.py", line 342, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py", line 66, in send_messages
mail = self._build_sg_mail(email)
File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py", line 125, in _build_sg_mail
base64_attachment = base64.b64encode(attachment[1])
File "/usr/lib/python3.5/base64.py", line 59, in b64encode
encoded = binascii.b2a_base64(s)[:-1]
TypeError: a bytes-like object is required, not 'str'
I checked if the file exists in the path, using if statement and yes it exists, is this something related to the way I am handling the files here? What should be the right approach?
this is the email sending I am functionality using:
def send_email_with_attachment(to_email, body, subject, attachment_content=None, main_type=None, file_name=None):
data = {'from_email': settings.DEFAULT_FROM_EMAIL, 'to': to_email,
'subject': subject, 'body': body}
logger.info("sending email")
email = EmailMessage(**data)
email.content_subtype = "html"
if attachment_content:
email.attach(file_name, attachment_content, main_type)
try:
email.send()
logger.info("Email sent")
except BaseException as e:
logger.exception(e)
Hi Junior put your html file in templates folder and write below code and make sure in settings.py file you wrote Templates settings.
import os
from django.conf import settings
from utils import email_utils
def pytest_sessionfinish(session, exitstatus):
to = ['xyz123#gmail.com']
body = 'test'
subject = 'coverage test'
attachment = "index.html"
coverage_html = os.path.join(settings.BASE_DIR + '/' + attachment)
email_utils.send_email_with_attachment(to, body, subject, coverage_html,
'application/html',
"index.html")
I'm using win32.client and trying to manipulate email body text.
This was working today but I think when testing I might have broken Outlook! When I try to call an index of a _Folders object, I get a type error that it is uncallable.
I use indexes to get into my nested folders. This was working until tonight and I haven't changed any of the code.
import win32com.client
import urllib.parse
import webbrowser
from pyshorteners import Shortener
application = win32com.client.Dispatch('Outlook.Application')
namespace = application.GetNamespace('MAPI')
# 6 is the number for the main inbox
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox(3)
mobile_folder_directory = mobile_folder.Folders
mobile_script_folder = mobile_folder_directory(2)
# using Items method to parse specific email files within the folder
messages = inbox_folder.Items
I get this error:
File "mail1.py", line 10, in mobile_folder = inbox_folders(3) TypeError: '_Folders' object is not callable
I was messing around with other code trying to monitor my inbox for new mail.
I ran some of this code in another file with some modifications to match my inboxes
import ctypes # for the VM_QUIT to stop PumpMessage()
import pythoncom
import win32com.client
import sys
# outlook config
SHARED_MAILBOX = "Your Mailbox Name"
# get the outlook instance and inbox folder
session = win32com.client.Dispatch("Outlook.Application").Session
user = session.CreateRecipient(SHARED_MAILBOX)
shared_inbox = session.GetSharedDefaultFolder(user, 6).Items # 6 is Inbox
class HandlerClass(object):
def OnItemAdd(self, item):
print("New item added in shared mailbox")
if item.Class == 43:
print("The item is an email!")
outlook = win32com.client.DispatchWithEvents(shared_inbox, HandlerClass)
def main():
print("Starting up Outlook watcher")
pythoncom.PumpMessages()
if __name__ == "__main__":
try:
status = main()
sys.exit(status)
except KeyboardInterrupt:
print("Terminating program..")
ctypes.windll.user32.PostQuitMessage(0)
sys.exit()
My suspicion is that it changed something with Outlook versions.
I also got something saying that a MAPIFolder object isn't callable. My research was showing this is an old, unsupported Outlook protocol.
Here's more data when I try to index my folders:
>>> inbox_folder
<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x12191504>
>>> inbox = inbox_folder.Folders
>>> inbox
<win32com.gen_py.Microsoft Outlook 16.0 Object Library._Folders instance at 0x46668848>
>>> inbox(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_Folders' object is not callable
I still don't know what broke it, but it turns out that searching folders by index wasn't working anymore.
The solution was now searching by folder name:
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox["Mobile"]
mobile_script_folder = mobile_folder.Folders["Mobile_4_4_Alpha"]
not sure why it fixed it but it did. yay!
don't know why but delete this file work in my case.
C:\Users\[user name]\AppData\Local\Temp\gen_py\[python version]\00062FFF-0000-0000-C000-000000000046x0x9x6.py
credit: https://blog.csdn.net/ericatardicaca/article/details/90721909
import smtplib
smtpserver = s.connect("mail.btinternet.com", 465)
SMTP.helo("mail.btinternet.com")
SMTP.ehlo("mail.btinternet.com")
file = open("Combo.txt", "r")
for line in file:
x = line.split(":")
user = x[0]
password = x[1]
s.login(user, password)
print("[+] Password Found: %s" % password)
if smtplib.SMTPAuthenticationError:
print("Incorrect")
Here's my code. It checks a list of email/password combinations from a file to see if it is on a specific server (in my case BT).
But I am having trouble with the library names, I am not sure what to use. I checked on python docs but it wasn't clear enough, if someone can tell me as to what is incorrect I would deeply appreciate it.
Error received.
This will also give me errors for the other incorrect library names
Traceback (most recent call last):
File "main.py", line 3, in <module>
smtpserver = s.connect("mail.btinternet.com", 465)
NameError: name 's' is not defined
exited with non-zero status
For your problem I think the reason why as to your libraries are not working properly is because you're calling your imported library inconsistently:
e.g. sometimes you type 's.xxxxx', sometimes you type 'SMTPlib.xxxxx' for your module attributes, you should import smtplib as 's'.
So what does this is it stores the library in a short form named 's', so whenever you call a module or use a function from the library, you don't have to type the full '.smtplib' but instead just type a '.s' extension behind the specific function:
import smtplib as s
smtpserver = s.connect("mail.btinternet.com", 465)
s.helo("mail.btinternet.com")
s.ehlo("mail.btinternet.com")
file = open("Combo.txt", "r")
for line in file:
x = line.split(":")
user = x[0]
password = x[1]
s.login(user, password)
print("[+] Password Found: %s" % password)
if s.SMTPAuthenticationError:
print("Incorrect")
Should fix your problems now. remember to call functions from the specific library name in a consistent manner ('s').
So I'm working on a Python script to extract text from an email and following these instructions to do so. This is the script thus far:
import imapclient
import pprint
import pyzmail
mymail = "my#email.com"
password = input("Password: ")
imapObj = imapclient.IMAPClient('imap.gmail.com' , ssl=True)
imapObj.login(mymail , password)
imapObj.select_folder('INBOX', readonly=False)
UIDs = imapObj.search(['SUBJECT Testing'])
rawMessages = imapObj.fetch([5484], ['BODY[]'])
message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
However I'm getting this error:
message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
KeyError: 5484
5484 being the ID for the email that the search function finds. I've also tried putting UIDs in instead of 5484, but that doesn't work either. Thanks in advance!
Thank you #Madalin Stroe .
I use python3.6.2 and pyzmail1.0.3 on Win10.
When I run
message = pyzmail.PyzMessage.factory(rawMessages[4]['BODY[]'])
The ERR shows like this:
Traceback (most recent call last):
File "PATH/TO/mySinaEmail.py", line 42, in <module>
message = pyzmail.PyzMessage.factory(rawMessages[4]['BODY[]'])
KeyError: 'BODY[]'
When I modified this to message = pyzmail.PyzMessage.factory(rawMessages[4][b'BODY[]']), it run well.
Try replacing ['BODY[]'] with [b'BODY[]']