替换已发送电子邮件中的字符串 [英] Replace a string in a sent email
问题描述
以下代码创建并发送一封简单的电子邮件.发送电子邮件后,它将替换电子邮件正文中的字符串.
The following code creates and sends a simple email. After the email is sent it replaces a string in the email body.
当我使用调试器的单步执行功能执行代码时,我的代码有效.当我在objMsg.Send
指令后添加带有单击以继续"按钮的MsgBox指令时,它也可以工作.当我不间断地执行宏时,它不起作用,但告诉我在宏运行时Outlook无法将电子邮件保存到文件夹中.
My code works when I use the debugger’s single-step feature to execute the code. It also works when I add a MsgBox instruction with a "click to continue" button after the objMsg.Send
instruction. It does not work when I execute the macro without interruption, but tells me that Outlook cannot save an email to the folder when a macro is running.
Sub CreateNewMessage()
objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)
With objMsg
.To = "mblasberg@inoxel.com"
.subject = "This is the subject"
.BodyFormat = olFormatHTML
.Body = "How are you doing?"
End With
objMsg.Send
' The following code replaces in the email body the string "you" with "they"
' Because I could not find how to open the "last sent" email,
' I used the "Sent Items" folder email count as as the pointer
' to the last email.
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = _
myNameSpace.GetDefaultFolder(olFolderSentMail)
Dim EmailCount As Integer
EmailCount = myFolder.Items.Count
Set myItem = myFolder.Items(EmailCount)
myItem.HTMLBody = replace(myItem.HTMLBody, "you", "they")
myItem.Save
End Sub
推荐答案
您执行的延迟操作足以完成发送.在没有延迟的情况下,该消息仍不在已发送邮件"文件夹中.
The delaying actions you take are enough for the send to complete. Without the delay the message is not yet in the Sent items folder.
您可以在代码中以适当的条件使用ItemAdd,以便它处理适用的消息.
You could instead use ItemAdd with appropriate conditions in the code so it processes applicable messages.
这将处理最近添加到已发送邮件"文件夹中的项目.
This will process the item most recently added to the Sent Items folder.
ThisOutlookSession的代码
Code for ThisOutlookSession
Option Explicit
Private WithEvents sItems As Items
Private Sub Application_Startup()
Dim objNS As NameSpace
Set objNS = GetNamespace("MAPI")
' default local Sent Items folder
Set sItems = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub sItems_ItemAdd(ByVal item As Object)
If TypeName(item) = "MailItem" Then
' ******************
' do something here with item
' ******************
Debug.Print item.subject
End If
End Sub
此未经测试的代码有错别字的来源. 在Outlook中收到新邮件后,如何触发宏运行?
Source in case this untested code has typos. How do I trigger a macro to run after a new mail is received in Outlook?
这篇关于替换已发送电子邮件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!