Outlook Check Message Type - python

I’m using a python package called win32com to directly access and scrape the inboxes from Outlook. As the Outlook application is setup to have multiple email accounts, I’ve had to adapt my code to read messages from multiple email accounts. However, the messages contains calendar invites and I just want email messages to be scraped. Is there a way to filter the messages based on type?
Outlook = client.Dispatch(“Outlook.Application”).GetNameSpace(“MAPI”)
Messages = outlook.Folders(“test#test.com).Folders(“Inbox”)
For msg in messages:
#Do Something

Yes, you need to check if the object is of type OlObjectClass.olMail, which is represented by value 43. You can check all enumerations here.
Outlook = client.Dispatch(“Outlook.Application”).GetNameSpace(“MAPI”)
Messages = outlook.Folders(“test#test.com).Folders(“Inbox”)
for msg in messages:
if msg.Class == 43: # OlObjectClass.olMail
#Do Something

Related

Sending emails with outlook using Python and HTML

How do I successfully use a sender account with a password that is not already signed in to on the Outlook application on my laptop? I want to send a message from the example account, "from#outlook.com" but it has a password. I have this password. Am I able to enter this into the existing code?
import win32com.client as client
import datetime,time
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="to#outlook.com"
message.CC=""
message.BCC=""
From = "from#outlook.com"
#password = ""
message.Subject="Subject text here"
message.BodyFormat = 2
message.HTMLBody = "<html><h2><span style='color:red'>There is an error with the file </b></span></h2> <body>Please check your submission and try again </body></html>"
message.Save()
message.Display()
time.sleep(5)
message.Send()
Firstly, MailItem object does not expose the From property. It exposes read-only Sender / SenderEmailAddress / SenderName properties, but they obviously cannot be set. You can set the MailItem.Account property to an instance of the Account object retrieved from the Application.Session.Accounts collection, but that requires you to configure the relevant account in Outlook first.
As a general rule, Outlook wont' let you send from an arbitrary one-off account not previously configured in Outlook.

receiving emails with python api O365

I am just starting out in Python and I am trying to accomplish a manual task I have heard is on the simpler side to accomplish with python. My company uses Office 365 for their emails and I want to retrieve an email attachment and store it locally so I can save time . So far have established how to send a simple email, call the names of the folders in my account but I cannot figure out how to read any specific email .
my idea goes a little like this ,
from O365 import Account, message,mailbox
credentials = ('username', 'given password')
account = Account(credentials)
mailbox = account.mailbox()
mail_folder = mailbox.inbox_folder()
mail_folder = mailbox.get_folder(folder_name='Inbox')
print(mail_folder)
#_init__(*,parent= Inbox, con=None,**kwargs)
Message_body = message.body()
message.get_subject('email subject here!')
print(Message.body)
right now I am lost and trying anything within the O365 documentation page but the message module does not have the attribute subject according to how I am using it . Any guidance would be much appreciated
From your example - it's not clear if you are authenticated or not...
If you are then you will be able to list the mailbox folders. In the case below - you can access the inbox and then list the sub-folders:
from O365 import Account, Connection, MSGraphProtocol, Message, MailBox, oauth_authentication_flow
scopes=['basic', 'message_all']
credentials=(<secret>, <another secret>)
account = Account(credentials = credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
account.authenticate(scopes=scopes)
account.connection.refresh_token()mailbox = account.mailbox()
inbox = mailbox.get_folder(folder_name='Inbox')
child_folders = inbox.get_folders(25)
for folder in child_folders:
print(folder.name, folder.parent_id)
This part will allow you to list folders (and also messages).
If I look at your code - it looks as though you are trying to do both?
Try doing something like the following to get the hang of paging through your inbox:
for message in inbox.get_messages(5):
if message.subject == 'test':
print(message.body)
Note that I'm looping through the first 5 messages in the inbox looking for a message with subject 'test'. If it finds the message - then it prints the body.
Hopefully this will shed a little light.

Create outlook draft email in python with out launching outlook application

I need to create an email draft and save in msg format without launching the outlook application.
(Or)
I have an existing draft msg file, I need to modify the sender, body, and attachment to that file and save as msg file.
I tried win32 it is working fine, but it is launching the outlook application in my system. In my server, there is no outlook application.
Can you please tell me is there any other ways to generate the msg file.
If you don't want to to use the Outlook Object Model, you are pretty much limited to either using a library like Aspose (it handles MSG files without having to install Outlook, but your mileage may vary) or Redemption (disclosure: I am its author) - it requires the MAPI system to be installed (which means Outlook must be installed), but it won't start Outlook if you are using RDOSession.CreateMsgFile (ollowed by setting various RDOMail properties and/or importing an existing MSG file using RDOMail.Import followed by RDOMail.Save.
Update per OP request.
I don't use Python, but in VB script it would be something like the following:
Set Session = CreateObject("Redemption.RDOSession")
set newMsg = Session.CreateMessageFromMsgFile("c:\temp\new.msg")
newMsg.Import("c:\temp\template.msg", 3)
newMsg.Body = "updated body"
newMsg.Save
You can create an email draft and save it as MSG with Aspose.Email for Python via .NET using the code sample given below:
eml = MailMessage()
# Set from, to, subject and body properties
eml.from_address = "sender#domain.com";
eml.to.append("receiver#domain.com");
eml.subject = "This is test message";
eml.body = "This is test body";
# Create an instance of the MapiMessage class and pass MailMessage as argument
outlookMsg = MapiMessage.from_mail_message(eml);
# Save the message (MSG) file
strMsgFile = "CreatingAndSavingOutlookMessages_out.msg"
outlookMsg.save(dataDir + strMsgFile);
Note: I am working as Support developer/ Evangelist at Aspose.

How to attach a calendar invite to SES send_raw_email?

I use send_raw_email to send emails with HTML content and file attachments. How do I insert an ical/ics invite to the email?
I use icalendar to generate ics content.
This is what I came up with so far, but it shows in Gmail as a file attachment.
if calendar_reminder_date:
cal = Calendar()
cal.add('prodid', '-//My calendar product//mxm.dk//')
cal.add('version', '2.0')
cal.add('calscale', 'GREGORIAN')
cal.add('method', 'REQUEST')
event = Event()
event['dtstart'] = calendar_reminder_date.strftime("%Y%m%dT%H%M%SZ")
event['dtstamp'] = calendar_reminder_date.strftime("%Y%m%dT%H%M%SZ")
event['summary'] = 'Python meeting about calendaring'
cal.add_component(event)
attachment_part = MIMEText(cal.to_ical())
print repr(cal.to_ical())
del attachment_part['Content-Type']
attachment_part.add_header('Content-Type', 'text/calendar', name='invite.ics')
attachment_part.add_header('Content-Disposition', 'attachment', filename='invite.ics')
msg.attach(attachment_part)
Hard to tell without seeing the actual full MIME message as received on the Google side but there are definitely several things missing here:
a calendar REQUEST must have an ORGANIZER property, as well as at least one ATTENDEE property with a value corresponding to the email address of the gmail user (prefixed with a mailto:).
your content-type is missing a METHOD=REQUEST parameter and you probably do not want to set any content-disposition.
See also Multipart email with text and calendar: Outlook doesn't recognize ics

How to send myself an email notification when a suds job is done?

I'm learning to use suds in a python script to send SQL queries to a database. I'd like to able to send myself an email when the query job is finished (it has a job ID so I'm able to check its status). How do I do that?
This is how you send an email via python just fill in the blanks and input it to your code:
import smtplib
content = ("Content to send")
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('your_email#gmail.com','123your_password')
mail.sendmail('your_email#gmail.com','destination_email#gmail.com',content)
mail.close()
print("Sent")
(you dont have to use gmail as most addresses will still work through the gmail smtp)
If email is not required, you can also send chat messages to yourself.
Two projects achieving this :
Nimrod, for Facebook Messenger : https://www.nimrod-messenger.io/
Telegram Middleman, for Telegram : https://github.com/n1try/telegram-middleman-bot
I just wrote a Python decorator for this purpose. You can realize it in one line.
https://github.com/Wenzhi-Ding/py_reminder
from py_reminder import monitor
#monitor('SQL Query of xxx')
def query(sql):
...send your query...
query()
Once this function finishes / or is caught an error, you will get an email notification with some brief information.

Categories

Resources