问题
Someone created a nice email template in outlook and sent it to me for automation.
I opened the email in HTML, and used that HTML to recreate the exact email images, formatting and all.
I can send this email out just fine, but I was then asked if I could save all the email files in a folder so that one could click on it and have it open up in their outlook (a .msg file).
I can save my email as an .mht and .elm file, but neither will open in outlook.
Seemed like an easy request...
msgRoot = MIMEMultipart('related')...
...
...
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('no alternative text version')
msgAlternative.attach(msgText)
msgText = MIMEText("""
...
...#too much going on here to paste. formatting and attaching images.
...
The part where I can successfully save this as .mht file:
with open("C:/LOCAL/test/"+var+'.mht', 'w+') as out:
gen = email.generator.Generator(out)
gen.flatten(msgRoot)
Is there an easy way to just save this as the .msg file so that it opens in the client? Like a preloaded email file. You open it, it's addressed etc... just need to hit send.
回答1:
Work with SaveAs Method [MSDN] with OlSaveAsType to get the correct file format
Example
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(win32com.client.constants.olFolderInbox)
SubFolder = Inbox.Folders["folder name"]
for Item in SubFolder.Items:
try:
Item.SaveAs("D:\\Temp\\email.msg", 3) # OlSaveAsType 3
except Exception as e:
print(e)
OlSaveAsType
+--------------+----+---------------------------------------+ | olDoc | 4 | Microsoft Office Word format (.doc) | | olHTML | 5 | HTML format (.html) | | olICal | 8 | iCal format (.ics) | | olMHTML | 10 | MIME HTML format (.mht) | | olMSG | 3 | Outlook message format (.msg) | | olMSGUnicode | 9 | Outlook Unicode message format (.msg) | | olRTF | 1 | Rich Text format (.rtf) | | olTemplate | 2 | Microsoft Outlook template (.oft) | | olTXT | 0 | Text format (.txt) | | olVCal | 7 | VCal format (.vcs) | | olVCard | 6 | VCard format (.vcf) | +--------------+----+---------------------------------------+
来源:https://stackoverflow.com/questions/60536289/how-to-save-html-email-as-an-outlook-file-using-python