http://community.youkuaiyun.com/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
http://www.freevbcode.com/ShowCode.Asp?ID=6401
| 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
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)
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 = "")
myMessage = New MailMessage()
With myMessage
.To = sendTo
.From = From
.Subject = Subject
.Body = Body
.BodyFormat = MailFormat.Text
'CAN USER MAILFORMAT.HTML if you prefer
If BCC <> "" Then .Bcc = ""
.Attachments.Add(AttachmentFile)
SmtpMail.SmtpServer = SMTPServer
SmtpMail.Send(myMessage)
Throw myexp
End Try
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 i, iCnt As Integer
myMessage = New MailMessage()
With myMessage
.To = sendTo
.From = From
.Subject = Subject
.Body = Body
.BodyFormat = MailFormat.Text
'CAN USER MAILFORMAT.HTML if you prefer
If BCC <> "" Then .Bcc = ""
iCnt = AttachmentFiles.Count - 1
For i = 0 To iCnt
If FileExists(AttachmentFiles(i)) Then _
.Attachments.Add(AttachmentFiles(i))
Next
SmtpMail.SmtpServer = SMTPServer
SmtpMail.Send(myMessage)
Catch myexp As Exception
Throw myexp
End Try
End Sub
As Boolean
If Trim(FileFullPath) = "" Then Return False
Return f.Exists
'Created by Chad M. Kovac
'Tech Knowledgey, Inc.
'http://www.TechKnowledgeyInc.com
Dim strDomainType As String
Dim strDomainName As String
Const sInvalidChars As String = "!#$%^&*()=+{}[]|/;:'/?>,< "
Dim i As Integer
If Not bCK Then GoTo ExitFunction
If Not bCK Then GoTo ExitFunction
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
bCK = Len(Left(strCheck, InStr(1, strCheck, "@") - 1)) > 0
Else
bCK = False
End If
If Not bCK Then GoTo ExitFunction
bCK = Not InStr(1, strCheck, "@") > 0 'Check to see if there are too many @'s
If Not bCK Then GoTo ExitFunction
bCK = Len(strDomainType) > 0 And InStr(1, strCheck, ".") < Len(strCheck)
If Not bCK Then GoTo ExitFunction
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
ValidEmail = bCK
End Function
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
Get
Return _smtpServer
End Get
Set(ByVal Value As String)
_smtpServer = Value
End Set
End Property
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
Dim em As New MailMessage
If Not (UserName Is Nothing) And Not (Password Is Nothing) Then
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
End Try
End Function 'Send
End Class 'SystemMail
709

被折叠的 条评论
为什么被折叠?



