Условно запретить Outlook от отправки электронной почты на основе адресов отправителя и получателя

У меня есть несколько учетных записей электронной почты в Outlook 2007 (например, [email protected], [email protected] и т. Д.). Иногда, обычно в результате функции автозаполнения, я по ошибке отправляю письмо с адреса [email protected] получателю, который должен получать почту только от [email protected]).

Эти ограничения между адресами электронной почты от (выбранная мной учетная запись электронной почты) и получателя (Кому или CC) обычно могут быть определены по имени домена.

Например, [email protected] не следует отправлять на домен-получателяX.com и домен- получателяY.com. И [email protected] не должен отправлять на адрес recipient-domain1.com и recipient-domain2.com.

Поэтому было бы хорошо явно определить или «жестко закодировать» эти ограничения домена для каждой учетной записи электронной почты в сценарии VBA или текстовом файле.

Итак, как с помощью VBA или других средств я могу реализовать проверку адресов электронной почты, чтобы предотвратить отправку электронного письма, если одно из этих ограничений нарушается.

Открыт также и для других, более элегантных решений.

Спасибо.


person splounx    schedule 08.04.2011    source источник


Ответы (2)


Это позволяет отображать электронные письма по адресу. Я не могу похвастаться этим, в основном это несколько разных кодов, опубликованных в Интернете, которые объединены в один. Тем не менее, он работает надежно и должен помочь вам достичь того, чего вы хотите. Это используется в нашей компании для отправки всех отправленных извне электронных писем в общую папку HR reviews.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    If Item.Class <> olMail Then Exit Sub
    Dim objMail As MailItem
    Set objMail = Item
    Dim NotInternal As Boolean
    NotInternal = False
    Dim objRecip As Recipient
    Dim objTo As Object
    Dim str As String
    Dim res As Integer
    Dim strBcc As String
    On Error Resume Next
    Const PidTagSmtpAddress As String = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
    Dim i As Integer
    Dim objRecipColl As Recipients
    Set objRecipColl = objMail.Recipients
    Dim objOneRecip As Recipient
    Dim objProp As PropertyAccessor
    For i = 1 To objRecipColl.Count Step 1
        Set objOneRecip = objRecipColl.Item(i)
        Set objProp = objOneRecip.PropertyAccessor
        str = objProp.GetProperty(PidTagSmtpAddress)
        If Len(str) >= 17 Then  'Len of email address screened.  
            If UCase(Right(str, 17)) <> "@COMPANYEMAIL.COM" Then NotInternal = True
        Else
            NotInternal = True
        End If
    Next
    If NotInternal = True Then
        strBcc = "[email protected]"
        Set objRecip = objMail.Recipients.Add(strBcc)
        objRecip.Type = olBCC
            If Not objRecip.Resolve Then
                strMsg = "Could not resolve the Bcc recipient. " & _
                         "Do you still want to send the message?"
                res = MsgBox(strMsg, vbYesNo + vbDefaultButton1, _
                        "Could Not Resolve Bcc Recipient")
                If res = vbNo Then
                    Cancel = True
                End If
            End If
    End If
    Set objRecipColl = Nothing
    Set objRecip = Nothing
    Set objOneRecip = Nothing
    Set objMail = Nothing
    Set objTo = Nothing
    Set oPA = Nothing
End Sub
person Ken    schedule 22.07.2011

Я изменил код, чтобы его было немного легче читать, фактически тот же код стал немного аккуратнее.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

If Item.Class <> olMail Then Exit Sub

Dim sCompanyDomain As String: sCompanyDomain = "companydomain.com"

Const PidTagSmtpAddress As String = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"

On Error Resume Next
Dim oMail As MailItem: Set oMail = Item
Dim oRecipients As Recipients: Set oRecipients = oMail.Recipients
Dim bDisplayMsgBox As Boolean: bDisplayMsgBox = False

Dim sExternalAddresses As String
Dim oRecipient As Recipient

For Each oRecipient In oRecipients

    Dim oProperties As PropertyAccessor: Set oProperties = oRecipient.PropertyAccessor
    Dim smtpAddress As String: smtpAddress = oProperties.GetProperty(PidTagSmtpAddress)

    Debug.Print smtpAddress

    If (Len(smtpAddress) >= Len(sCompanyDomain)) Then

        If (Right(LCase(smtpAddress), Len(sCompanyDomain)) <> sCompanyDomain) Then

            ' external address found
            If (sExternalAddresses = "") Then

                sExternalAddresses = smtpAddress

            Else

                sExternalAddresses = sExternalAddresses & ", " & smtpAddress

            End If

            bDisplayMsgBox = True

        End If

    End If

Next

If (bDisplayMsgBox) Then

    Dim iAnswer As Integer
    iAnswer = MsgBox("You are about to send this email externally to " & sExternalAddresses & vbCr & vbCr & "Do you want to continue?", vbExclamation + vbYesNo, "External Email Check")

    If (iAnswer = vbNo) Then
        Cancel = True
    End If

End If

End Sub
person Abu Belal    schedule 12.07.2013