如何检查电子邮件是否不是@ courts.state.dc.us,如果不是,则抛出错误

时间:2014-11-05 20:03:01

标签: vb.net

我有一个vb.net代码。如果电子邮件有 @ courts.state.dc.us ,我只想发送电子邮件。如何检查电子邮件是否有@ courts.state.dc.us。如果电子邮件有例如jane.doe@gmail.com,我想抛出异常。 例外可以说“我们无法发送电子邮件,此电子邮件是无法审讯的电子邮件”。

这是我的visual studio 2010代码

'Send email
    If Not aobjXmlInputDoc.DocumentElement.SelectSingleNode("IntegrationConditions/IntegrationCondition/NotificationEvent[@notificationType='PetitionerNotification']") Is Nothing Then
    strPetitionerEmail = aobjXmlInputDoc.DocumentElement.SelectSingleNode("IntegrationConditions/IntegrationCondition/NotificationEvent[@notificationType='PetitionerNotification']/@petitionerEmailAddress").InnerText
    If Msc.Integration.Utility.Library.v4.ProgramExecution.GetRuntimeEnvironment <> "PROD" Then
    'Make sure email is to court email address e.g mike.mike@courts.state.dc.us 
    'If the email is not xyz@courts.state.mn.us
    'Throw an exception
    'The email was not sent. Email was none court email
    End If
aobjBroker.PostMessageWarehouseInformationalMessage("Sending petitioner notification", 1)
Msc.Integration.Utility.Library.v4.Email.Send("DC.District.Court@Dccourts.gov", strPetitionerEmail, "Service Information", CreateEmail(aobjXmlInputDoc, objSimpleType), , , True)
End If

1 个答案:

答案 0 :(得分:3)

也许是一个简单的EndsWith()检查:

If Not strPetitionerEmail.Trim().EndsWith("@courts.state.dc.us", _
    StringComparison.OrdinalIgnoreCase) Then
    Throw New ArgumentException("Invalid e-mail. E-mail not sent.", "strPetitionerEmail")
End If

您也可以使用ArgumentOutOfRangeException,因为参数超出了有效范围(只有一个,但是......)的电子邮件域。

然后从调用代码中,您可以捕获异常:

Try
    SendEmail() ' or however you plan on invoking the above code
Catch ex As ArgumentException
    ' Log the exception?
    ' ex.ParamName contains the parameter name, ex.Message the message
Catch ex As Exception
    ' Log the [unhandled] exception?
    ' ex.Message contains the message
End Catch

请注意,我事先Trim()编辑了电子邮件地址,而忽略了它的外壳。