Click here to Skip to main content
15,882,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm a beginner trying to achieve the below in my python script: Can anyone help me on this? I'm stuck at step2.

1. Input: A locally saved outlook mail (*.msg) path
2. Go to the specific mail file and Copy the entire body of the mail
3. Create a new mail and paste the contents into new mail

What I have tried:

Python
import win32com.client as win32

   ########### Functions
   def getMailBody(msgFile):
       start_text = "<html>"
       end_text = "</html>"
       with open(msgFile) as f:
           data=f.read()
       return data[data.find(start_text):data.find(end_text)+len(end_text)]

   def releaseMail(body, subject, recipient):
       outlook = win32.Dispatch('outlook.application')
       mail = outlook.CreateItem(0)
       mail.To = recipient
       mail.Subject = subject
       mail.HtmlBody = body
       mail.Display(True)

   ############### Main ################
   msgFile = "C:\\RELM\\testMsg.msg"
   mailTo = "mymail@myserver.com"
   mailSubject = "Test message"
   mailBody = getMailBody(msgFile)
   releaseMail(mailBody, mailSubject, mailRecipient)



Below is the error I'm getting.
================================
File "C:\Python\Python38-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 924: character maps to <undefined>
Posted
Updated 27-Nov-22 17:45pm

for message in messages:
    ## Assigning the values
    subject = message.Subject.encode('utf-8')
    subjectS = str(subject)
    body = message.body.encode('utf-8')
    bodyS = str(body)
    znder = message.sender


Then you simply replace all \n with new line feed, and so on.
 
Share this answer
 
I modified my function as below and now I can successfully execute the script. But the result mail lost all the original mail format in the body. Now how to retain the original format?

def getMailBody(msgFile):
    outlook = win32.Dispatch('outlook.application').GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(msgFile)
    return msg.Body
 
Share this answer
 
Curious, I looked on web. Everywhere the response was to read with right encoding format to resolve it.

So, instead of open(msgFile), try:
Python
open(msgFile, encoding='utf8')


Similar error solves:
python - UnicodeDecodeError: 'charmap' codec can't decode byte 0x81[^]
windows - UnicodeDecodeError: 'charmap' codec can't decode byte X [^]

Try out.
 
Share this answer
 
Comments
Member 15033078 29-Dec-20 10:52am    
@sandeep Mewara
Tried but i didn't work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900