CSDN博客

img 2066

使用System.Web.Mail通过需验证的邮件服务器发送邮件

发表于2004/9/21 16:35:00  1669人阅读

http://community.csdn.net/Expert/topic/3198/3198073.xml?temp=.3856623

使用System.Web.Mail通过需验证的邮件服务器发送邮件,下面是Scott Water在dotText中写的一个发邮件的类,使用起来比较方便,整个类的代码如下:

using System;

using System.Web.Mail;

 

namespace MYtest

{

     ///

     /// SystemMail 的摘要说明。

     ///

     public class SystemMail

     {

         private string _adminEmail;

         private string _smtpServer = "localhost";

         private string _password;

         private string _userName;

 

         public SystemMail()

         {            

         }

 

        

         public string AdminEmail

         {

              get{return _adminEmail;}

              set{_adminEmail = value;}

         }

 

        

         public string SmtpServer

         {

              get{return _smtpServer;}

              set{_smtpServer = value;}

         }

 

        

         public string Password

         {

              get{return _password;}

              set{_password = value;}

         }

 

        

         public string UserName

         {

              get{return _userName;}

              set{_userName = value;}

         }

 

         public bool Send(string to, string from, string subject, string message)

         {

              try

              {

                   MailMessage em = new MailMessage();

                   em.To = to;

                   em.From = from;

                   em.Subject = subject;

                   em.Body = message;

 

                   //Found out how to send authenticated email via System.Web.Mail at http://SystemWebMail.com (fact 3.8)

                   if(this.UserName != null && this.Password != null)

                   {

                       em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");   //basic authentication

                       em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", this.UserName); //set your username here

                       em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", this.Password); //set your password here

                   }

 

                   SmtpMail.SmtpServer = this.SmtpServer;

                   SmtpMail.Send(em);

                   return true;

              }

              catch

              {

                   return false;

              }

          }

 

     }

}

需要更多信息可以查看http://SystemWebMail.com

 

 

 

Author: Anonymous
Category: VB.NET/ASP.NET
Type: Snippets
Difficulty: Beginning

Version Compatibility:  Visual Basic.NET  

More information: This articles explains everything about, how to send mail using the system.web.mail namespace.

This code has been viewed 12092 times.

Instructions: Copy the declarations and code below and paste directly into your VB project.


Declarations:
Sending Mail Using Dot net


 The System.Web.Mail namespace provides the classes for sending Email in Dot net.

MailMessage   Manage the mail message contents.

Properties

Attachment 
Specifies the list of the attachments that are transmitted with the message

Bcc 
A list of semicolon delimited email addresses that receive a Blind Carbon Copy of the message

Body 
Contains the message text that has to be sent.

BodyEncoding  
The encoding type of the email message.

BodyFormat 
Defines the content type of the body of the message

Cc 
A list of semicolon delimited email addresses that receive a Carbon Copy of the message

From  
The email address of the sender.

Header 
Specifies the custom headers which are transmitted with the
Message

Priority 
The priority of the email message

Subject  
Subject Line of the email message.

To 
email address of the recipient.

 

MailAttachments   Manage the mail attachment.

SmtpMail   Send email to the mail server.

 

 


Let us see it step by step

Create a Visual basic application
And drop following controls and set the properties accordingly

Control   Property


Label   Text  : Smtp Server

TextBox   Name : txtSMTPServer

Label   Text  : From

TextBox   Name : txtFrom

Label   Text : From Display Name

TextBox   Name : txtFromDisplayName

Label   Text :  Recipient

TextBox   txtTo

Label   Text : Attachment

ListBox   Name : lstAttachment

Label   Text : Subject

TextBox   Name : txtSubject

Label   Text : Message

TextBox   Name : txtMessage
   Multiline : True
   Scrollbars : Both

Button   Text : Add attachment
   Name : BtnAdd


Button   Text : Remove attachment
   Name : btnRemove


Button   Text : Send
   Name : btnSend


CheckBox  Text: Send As HTML
   Name : chkFormat


OpenFileDialog  Name : OFD
   DefaultExt : *.*
   InitialDirectory : c:/
   Multiselect : true

    

Now let us see the coding part


Invoke the Code widow and type the following statement above the Class declaration
Imports System.Web.Mail
Within the Class declaration, in the general section declare variables required for this project

' Variable which will send the mail
Dim obj As System.Web.Mail.SmtpMail

'Variable to store the attachments
Dim Attachment As System.Web.Mail.MailAttachment

'Variable to create the message to send
Dim Mailmsg As New System.Web.Mail.MailMessage()   


Double click on the addattachment button to add the code

Type the following lines

'Show open dialogue box to select the files to attach
Dim Counter As Integer
OFD.CheckFileExists = True
OFD.Title = "Select file(s) to attach"
OFD.ShowDialog()

For Counter = 0 To UBound(OFD.FileNames)
lstAttachment.Items.Add(OFD.FileNames(Counter))
Next

Double Click on the Removeattachment button

Type the following lines

'Remove the attachments
If lstAttachment.SelectedIndex > -1 Then
lstAttachment.Items.RemoveAt(lstAttachment.SelectedIndex)
End If

 

Double Click on the Send button

Type the following lines


Dim Counter As Integer

'Validate the data
If txtSMTPServer.Text = "" Then
MsgBox("Enter the SMTP server info ...!!!", MsgBoxStyle.Information,  "Send Email")
Exit Sub
End If

If txtFrom.Text = "" Then
            MsgBox("Enter the From email address ...!!!", MsgBoxStyle.Information, "Send Email")
Exit Sub
End If

If txtTo.Text = "" Then
MsgBox("Enter the Recipient email address ...!!!", MsgBoxStyle.Information, "Send Email")
Exit Sub
End If

If txtSubject.Text = "" Then
MsgBox("Enter the Email subject ...!!!", MsgBoxStyle.Information, "Send Email")
Exit Sub
End If

'Set the properties
慉ssign the SMTP server
obj.SmtpServer = txtSMTPServer.Text
'Multiple recepients can be specified using ; as the delimeter
慉ddress of the recipient
Mailmsg.To = txtTo.Text


慪our From Address
慪ou can also use a custom header Reply-To for a different replyto address
Mailmsg.From = "/" & txtFromDisplayName.Text & "/ <" & txtFrom.Text & ">"


'Specify the body format
If chkFormat.Checked = True Then
Mailmsg.BodyFormat = MailFormat.Html   'Send the mail in HTML Format
Else
Mailmsg.BodyFormat = MailFormat.Text
End If

'If you want you can add a reply to header
'Mailmsg.Headers.Add("Reply-To", "Manoj@geinetech.net")
'custom headersare added like this
'Mailmsg.Headers.Add("Manoj", "TestHeader")

慚ail Subject
Mailmsg.Subject = txtSubject.Text

慉ttach the files one by one
For Counter = 0 To lstAttachment.Items.Count - 1
Attachment = New MailAttachment(lstAttachment.Items(Counter))
慉dd it to the mail message
            Mailmsg.Attachments.Add(Attachment)
Next

慚ail Body
Mailmsg.Body = txtMessage.Text
慍all the send method to send the mail
obj.Send(Mailmsg)

This application is now ready to run , try it. If you have any queries mail it to manoj@geinetech.net

 


 

Sending Email with Attachments (VB.NET/ASP.NET)
Imports System.Web.Mail
Imports System.IO
   'TWO FUNCTIONS
    'SAME EXCEPT FIRST TAKES A STRING FOR ATTACHMENT
    'SECOND TAKES AN ARRAY LIST SO YOU CAN SEND MULTIPLE
         'ATTACHMENTS
    'FROM: Email address FRom
    'TO: EMAIL address To
    'Subject: Subject; Body: MessageText
    'Optional CC, BCC: CC and bcc recipients
    'SMTPSERVER: Optional, if not specified
   'local machine is used
    'AttachmentFile (first function: Optional, file name)
    'AttachmentFiles (second function: Optional, list of    
        'attachments in form of an array list)
    Public Sub SendMailOneAttachment(ByVal From As String, _
      ByVal sendTo As String, ByVal Subject As String, _
      ByVal Body As String, _
      Optional ByVal AttachmentFile As String = "", _
      Optional ByVal CC As String = "", _
      Optional ByVal BCC As String = "", _
      Optional ByVal SMTPServer As String = "")
        Dim myMessage As MailMessage
        Try
            myMessage = New MailMessage()
            With myMessage
                .To = sendTo
                .From = From
                .Subject = Subject
                .Body = Body
                .BodyFormat = MailFormat.Text
                'CAN USER MAILFORMAT.HTML if you prefer
                If CC <> "" Then .Cc = CC
                If BCC <> "" Then .Bcc = ""
                If FileExists(AttachmentFile) Then _
                 .Attachments.Add(AttachmentFile)
            End With
            If SMTPServer <> "" Then _
               SmtpMail.SmtpServer = SMTPServer
            SmtpMail.Send(myMessage)
        Catch myexp As Exception
            Throw myexp
        End Try
    End Sub
Public Sub SendMailMultipleAttachments(ByVal From As String,_
    ByVal sendTo As String, ByVal Subject As String, _
    ByVal Body As String, _
    Optional ByVal AttachmentFiles As ArrayList = Nothing, _
    Optional ByVal CC As String = "", _
    Optional ByVal BCC As String = "", _
    Optional ByVal SMTPServer As String = "")
        Dim myMessage As MailMessage
        Dim i, iCnt As Integer
        Try
            myMessage = New MailMessage()
            With myMessage
                .To = sendTo
                .From = From
                .Subject = Subject
                .Body = Body
                .BodyFormat = MailFormat.Text
                'CAN USER MAILFORMAT.HTML if you prefer
                If CC <> "" Then .Cc = CC
                If BCC <> "" Then .Bcc = ""
                If Not AttachmentFiles Is Nothing Then
                    iCnt = AttachmentFiles.Count - 1
                    For i = 0 To iCnt
                        If FileExists(AttachmentFiles(i)) Then _
                          .Attachments.Add(AttachmentFiles(i))
                    Next
                End If
            End With
            If SMTPServer <> "" Then _
              SmtpMail.SmtpServer = SMTPServer
            SmtpMail.Send(myMessage)

        Catch myexp As Exception
            Throw myexp
        End Try
    End Sub
    Private Function FileExists(ByVal FileFullPath As String) _
     As Boolean
        If Trim(FileFullPath) = "" Then Return False
        Dim f As New IO.FileInfo(FileFullPath)
        Return f.Exists
    End Function
 
 
 
 
 
Check an Email Address for Validity (VB.NET and VB6)
Function ValidEmail(ByVal strCheck As String) As Boolean
'Created by Chad M. Kovac
'Tech Knowledgey, Inc.
'http://www.TechKnowledgeyInc.com
Dim bCK As Boolean
Dim strDomainType As String
Dim strDomainName As String
Const sInvalidChars As String = "!#$%^&*()=+{}[]|/;:'/?>,< "
Dim i As Integer
bCK = Not InStr(1, strCheck, Chr(34)) > 0 'Check to see if there is a double quote
If Not bCK Then GoTo ExitFunction
bCK = Not InStr(1, strCheck, "..") > 0 'Check to see if there are consecutive dots
If Not bCK Then GoTo ExitFunction
' Check for invalid characters.
If Len(strCheck) > Len(sInvalidChars) Then
    For i = 1 To Len(sInvalidChars)
        If InStr(strCheck, Mid(sInvalidChars, i, 1)) > 0 Then
            bCK = False
            GoTo ExitFunction
        End If
    Next
Else
    For i = 1 To Len(strCheck)
        If InStr(sInvalidChars, Mid(strCheck, i, 1)) > 0 Then
            bCK = False
            GoTo ExitFunction
        End If
    Next
End If
If InStr(1, strCheck, "@") > 1 Then 'Check for an @ symbol
    bCK = Len(Left(strCheck, InStr(1, strCheck, "@") - 1)) > 0
Else
    bCK = False
End If
If Not bCK Then GoTo ExitFunction
strCheck = Right(strCheck, Len(strCheck) - InStr(1, strCheck, "@"))
bCK = Not InStr(1, strCheck, "@") > 0 'Check to see if there are too many @'s
If Not bCK Then GoTo ExitFunction
strDomainType = Right(strCheck, Len(strCheck) - InStr(1, strCheck, "."))
bCK = Len(strDomainType) > 0 And InStr(1, strCheck, ".") < Len(strCheck)
If Not bCK Then GoTo ExitFunction
strCheck = Left(strCheck, Len(strCheck) - Len(strDomainType) - 1)
Do Until InStr(1, strCheck, ".") <= 1
    If Len(strCheck) >= InStr(1, strCheck, ".") Then
        strCheck = Left(strCheck, Len(strCheck) - (InStr(1, strCheck, ".") - 1))
    Else
        bCK = False
        GoTo ExitFunction
    End If
Loop
If strCheck = "." Or Len(strCheck) = 0 Then bCK = False
ExitFunction:
ValidEmail = bCK
End Function
 


 
Public Class myMail
        Private _adminEmail As String
        Private _smtpServer As String
        Private _password As String
        Private _userName As String

        Public Sub New()
        End Sub 'New

        Public Property AdminEmail() As String
            Get
                Return _adminEmail
            End Get
            Set(ByVal Value As String)
                _adminEmail = Value
            End Set
        End Property
 
        Public Property SmtpServer() As String
            Get
                Return _smtpServer
            End Get
            Set(ByVal Value As String)
                _smtpServer = Value
            End Set
        End Property
 
        Public Property Password() As String
            Get
                Return _password
            End Get
            Set(ByVal Value As String)
                _password = Value
            End Set
        End Property
 
 

        Public Property UserName() As String
            Get
                Return _userName
            End Get
            Set(ByVal Value As String)
                _userName = Value
            End Set
        End Property
 

        Public Function Send(ByVal [to] As String, ByVal from As String, ByVal subject As String, ByVal message As String) As Boolean
            Try
                Dim em As New MailMessage
                em.To = [to]
                em.From = from
                em.Subject = subject
                em.Body = message
 
                'Found out how to send authenticated email via System.Web.Mail at http://SystemWebMail.com (fact 3.8)
                If Not (UserName Is Nothing) And Not (Password Is Nothing) Then
                    em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1") 'basic authentication
                    em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", Me.UserName) 'set your username here
                    em.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", Me.Password) 'set your password here
                End If
                SmtpMail.SmtpServer = SmtpServer
                SmtpMail.Send(em)
                Return True
            Catch
            End Try
        End Function 'Send
    End Class 'SystemMail
 
0 0

相关博文

我的热门文章

img
取 消
img