Send mail from ASP.NET using your gmail account
from: http://www.aspcode.net/Send-mail-from-ASPNET-using-your-gmail-account.aspx
http://relevantcodes.com/cdo-send-email-from-yahoo-hotmail-live-aol-or-gmail/
http://www.codeproject.com/KB/IP/SendMailUsingGmailAccount.aspx?display=Print
2
3 string sToName, string sToEmail, string sHeader, string sMessage, bool fSSL)
4
5 {
6
7 if (sToName.Length == 0)
8
9 sToName = sToEmail;
10
11 if (sFromName.Length == 0)
12
13 sFromName = sFromEmail;
14
15
16
17 System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
18
19 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
20
21 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
22
23
24
25 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
26
27 if ( fSSL )
28
29 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";
30
31
32
33 if (sUserName.Length == 0)
34
35 {
36
37 //Ingen auth
38
39 }
40
41 else
42
43 {
44
45 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
46
47 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
48
49 Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
50
51 }
52
53
54
55 Mail.To = sToEmail;
56
57 Mail.From = sFromEmail;
58
59 Mail.Subject = sHeader;
60
61 Mail.Body = sMessage;
62
63 Mail.BodyFormat = System.Web.Mail.MailFormat.Html;
64
65
66
67 System.Web.Mail.SmtpMail.SmtpServer = sHost;
68
69 System.Web.Mail.SmtpMail.Send(Mail);
70
71 }
72
73
Now, the secret is the last parameter, bool fSSL. If true then we set the magic CDO field cdo/configuration/smtpusessl to true:
if ( fSSL )
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";
And that my folks is all we need. Specify true as last parameter and you will have SSL authentication. Which gmail for example uses so look at this example:
2
3 465,
4
5 "account@gmail.com",
6
7 "<accountpassword>",
8
9 "Your name",
10
11 "account@gmail.com",
12
13 "Stefan Receiver",
14
15 "receive@whatever.com",
16
17 "Test",
18
19 "Hello there Steff!",
20
21 true);
22
23
So secret to get mail working against gmail is: port 465 - server smtp.gmail.com and ssl = true.
碍于JMail本身对SSL之限制,若有Gmail发送信件需求朋友,可以透过CDO.Message实现
2
3 dim myMail
4
5 Set myMail=CreateObject("CDO.Message")
6
7 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
8
9 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
10
11 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
12
13 'Authentication method, ssl or not, Username and password for the SMTP Server
14
15 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
16
17 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
18
19 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "你的Gmail帐号"
20
21 myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "你的Gmail密码"
22
23 '-------------------------------------
24
25 myMail.Configuration.Fields.Update
26
27 myMail.From = "geovindu@gmail.com"
28
29 myMail.To = "Geovin Du<geovindu@163.com>"
30
31 myMail.Subject ="geovindu"
32
33 myMail.TextBody = "geovindu"
34
35 myMail.Send
36
37 set myMail=nothing
38
39 %>
40
41
-------------------------------------------------------------------------------------------------------------------
CDO 邮件元件使用方法
Microsoft从Windows Server 2000 及 Windows XP开始内建邮件元件已改为CDO
在之前的系统内建邮件元件则是 CDONTS,各位要注意,以下是CDO的用法
属性 说明
Subject 邮件的主旨
From 寄件人的电子邮件信箱
To 收件人的电子邮件,可用分号;或逗号,断开成多位收件人
CC 副本收件人的电子邮件,可用分号;或逗号,断开成多位收件人
BCC 密送副本收件人的电子邮件,可用分号;或逗号,断开成多位收件人
TextBody 邮件的本文-纯文字模式
HTMLBody 邮件的本文-HTML模式
方法 说明
Send 送出邮件
AddAttachment "c:\mydocuments\test.txt" 附件
CreateMHTMLBody "http://www.w3schools.com/asp/" 将一个网页用HTML格式送出
CreateMHTMLBody "file://c:/mydocuments/test.htm" 将本机硬碟中的一个网页用HTML格式送出
myMail.HTMLBodyPart.Charset = "UTF-8" 以UTF-8 可以发送多种语言,当然也要看接受方邮件的编码格式的兼容性
范例:
送出一封纯文字信件:
2
3 Set myMail=CreateObject("CDO.Message")
4
5 myMail.Subject="Sending email with CDO"
6
7 myMail.From="geovindu@gmail.com"
8
9 myMail.To="geovindu@dusystem.com"
10
11 myMail.TextBody="This is a message."
12
13 myMail.Send
14
15 set myMail=nothing
16
17 %>
18
19
vbscript code:
2 Class clsSendMail
3
4 Private oMessage 'CDO.Message Object
5 Private strFrom 'Sender's Email ID: XX@YY.COM
6 Public Body 'Body Text from Text File
7
8 '—————————————————————————————————————————————
9 ' Name: Sub Email (Public)
10 '
11 ' Purpose: Send Email Using CDO
12 '
13 ' Parameters:
14 ' sEmailID: Sender's Mail ID String
15 ' sPassword: Sender's Password String
16 ' sTo: Recipient's Mail ID String (Primary)
17 ' sCC: Recipient's Mail ID String (CC)
18 ' sSubject: Subject String
19 ' sBody: Body Message String
20 '
21 ' Return: -
22 '—————————————————————————————————————————————
23 Public Sub Send( sEMailID, sPassword, sTo, sCC, sSubject, sBody )
24 '—————————————————————————————————————————————
25 Dim oRegExp 'RegEx Object
26 Dim sDetails 'Report Details
27 Dim intStatus 'Report Status
28 Dim sStepName 'Report Step
29
30 'Sender ID has Class scope
31 Me.From = sEmailID
32 'Message Body
33 If sBody <> "" Then Me.Body = sBody
34
35 intStatus = micPass
36 sStepName = " Sent"
37
38 Set oRegExp = New RegExp
39 oRegExp.Global = True
40 oRegExp.Pattern = "<\w>|<\w\w>|<\w\d>"
41 Set oMatches = oRegExp.Execute( Me.Body )
42
43 'Build Message
44 With oMessage
45 .Subject = sSubject
46 .From = sEmailID
47 .To = sTo
48 .CC = sCC
49 'BCC Property can be added as well:
50 '.BCC = sBCC
51 'If HTML Tags found, use .HTMLBody
52 If oMatches.Count > 0 Then
53 .HTMLBody = Me.Body
54 Else
55 .TextBody = Me.Body
56 End If
57 End With
58
59 Set oMatches = Nothing
60 Set oRegExp = Nothing
61
62 With oMessage.Configuration.Fields
63 'Sender's Mail ID
64 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
65 "sendusername") = sEmailID
66 'Sender's Password
67 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
68 "sendpassword") = sPassword
69 'Name/IP of SMTP Server
70 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
71 "smtpserver") = cdoSMTPServer
72 'Server Port
73 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
74 "smtpserverport") = cdoOutgoingMailSMTP
75 'Send Using: (1) Local SMTP Pickup Service (2) Use SMTP Over Network
76 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
77 "sendusing") = cdoSendUsing
78 'Authentication Used: (1) None (2) Basic (3) NTLM
79 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
80 "smtpauthenticate") = cdoAuthenticationType
81 'SMTP Server Requires SSL/STARTTLS: Boolean
82 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
83 "smtpusessl") = cdoUseSSL
84 'Maximum Time in Seconds CDO will try to Establish Connection
85 .Item("http://schemas.microsoft.com/cdo/configuration/" &_
86 "smtpconnectiontimeout") = cdoTimeout
87 'Update Configuration Entries
88 .Update
89 End With
90
91 'Report Details
92 sDetails = "SMTP Server: " & cdoSMTPServer & vbLf
93 sDetails = sDetails & "Sender: " & sEMailID & vbLf
94 sDetails = sDetails & "Recipient: " & sTo & vbLf
95 sDetails = sDetails & "Server Port: " & cdoOutgoingMailSMTP & vbLf
96 sDetails = sDetails & "SSL Used: " & cdoUseSSL & vbLf
97 sDetails = sDetails & "Authentication Type: " & cdoAuthenticationType & vbLf
98 sDetails = sDetails & "SMTP Service Type: " & cdoSendUsing & vbLf & vbLf
99 sDetails = sDetails & "Subject: " & sSubject & vbLf & vbLf
100 sDetails = sDetails & "Body: " & sBody
101
102 On Error Resume Next
103 'Send Message
104 oMessage.Send
105 If Err.Number <> 0 Then
106 intStatus = micWarning
107 sStepName = " Not Sent"
108 sDetails = sDetails & vbLf & "Error Description: " & Err.Description
109 End If
110 On Error Goto 0
111
112 'If you're not using QTP, please disable the statement below:
113 Reporter.ReportEvent intStatus, "EMail" & sStepName, sDetails
114 End Sub
115
116 '—————————————————————————————————————————————
117 ' Name: Sub LoadBodyMessage (Public)
118 '
119 ' Purpose: Loads BodyText from a Text File
120 '
121 ' Parameters:
122 ' sCompleteFilePath: Complete Path to the Text File (Eg: "C:\MyDocs\MyMail.txt")
123 '
124 ' Return: -
125 '—————————————————————————————————————————————
126 Public Sub LoadBodyMessage( sCompleteFilePath )
127 '—————————————————————————————————————————————
128 CONST ForReading = 1
129 Dim oFSO, oFile
130
131 Set oFSO = CreateObject( "Scripting.FileSystemObject" )
132 Set oFile = oFSO.OpenTextFile( sCompleteFilePath, ForReading )
133 Me.Body = oFile.ReadAll
134 oFile.Close: Set oFile = Nothing
135
136 Set oFSO = Nothing
137 End Sub
138
139 '—————————————————————————————————————————————
140 ' Name: Class_Initialize (Private)
141 '
142 ' Purpose: Binds to the CDO Object
143 '
144 ' Parameters: -
145 '
146 ' Return: -
147 '—————————————————————————————————————————————
148 Private Sub Class_Initialize
149 '—————————————————————————————————————————————
150 Set oMessage = CreateObject( "CDO.Message" )
151 End Sub
152
153 '—————————————————————————————————————————————
154 ' Name: Class_Initialize (Private)
155 '
156 ' Purpose: Release the CDO Object
157 '
158 ' Parameters: -
159 '
160 ' Return: -
161 '—————————————————————————————————————————————
162 Private Sub Class_Terminate
163 '—————————————————————————————————————————————
164 Set oMessage = Nothing
165 End Sub
166
167 '—————————————————————————————————————
168 ' Name: Property cdoSendUsing (Private)
169 '
170 ' Purpose: Readonly property configuration for SMTP Service
171 '—————————————————————————————————————
172 Private Property Get cdoSendUsing 'As Integer
173 '—————————————————————————————————————
174 cdoSendUsing = 2 'Use SMTP Over The Network
175 'cdoSendUsing = 1 'Use Local SMTP Service Pickup Directory
176 End Property
177
178 '—————————————————————————————————————
179 ' Name: Property cdoTimeout (Private)
180 '
181 ' Purpose: Maximum time in seconds CDO will try to establish a connection
182 '—————————————————————————————————————
183 Private Property Get cdoTimeout 'As Integer
184 '—————————————————————————————————————
185 'cdoTimeout = 15 'Seconds
186 cdoTimeout = 45 'Seconds
187 'cdoTimeout = 75 'Seconds
188 End Property
189
190 '—————————————————————————————————————
191 ' Name: Property cdoAuthenticationType (Private)
192 '
193 ' Purpose: Type of Authentication to be used
194 '—————————————————————————————————————
195 Private Property Get cdoAuthenticationType 'As Integer
196 '—————————————————————————————————————
197 'cdoAuthenticationType = 0 'No Authentication
198 cdoAuthenticationType = 1 'Basic Authentication
199 'cdoAuthenticationType = 2 'NTML Authentication
200 End Property
201
202 '—————————————————————————————————————
203 ' Name: Property cdoOutgoingMailSMTP (Private)
204 '
205 ' Purpose: Server Port
206 '—————————————————————————————————————
207 Private Property Get cdoOutgoingMailSMTP 'As Integer
208 '—————————————————————————————————————
209 If InStr(1, Lcase(Me.From), "@gmail") <> 0 Then
210 cdoOutgoingMailSMTP = 465
211 ElseIf InStr(1, LCase(Me.From), "@aol") <> 0 Then
212 cdoOutgoingMailSMTP = 587
213 Else
214 cdoOutgoingMailSMTP = 25
215 End If
216 End Property
217
218 '—————————————————————————————————————
219 ' Name: Property cdoSMTPServer (Private)
220 '
221 ' Purpose: Name/IP of SMTP Server
222 '—————————————————————————————————————
223 Private Property Get cdoSMTPServer 'As String
224 '—————————————————————————————————————
225 If InStr(1, LCase(Me.From), "@yahoo") <> 0 Then
226 cdoSMTPServer = "smtp.mail.yahoo.com"
227 ElseIf InStr(1, LCase(Me.From), "@gmail") <> 0 Then
228 cdoSMTPServer = "smtp.gmail.com"
229 ElseIf InStr(1, LCase(Me.From), "@hotmail") <> 0 Or _
230 InStr(1, LCase(Me.From), "@live") <> 0 Then
231 cdoSMTPServer = "smtp.live.com"
232 ElseIf InStr(1, LCase(Me.From), "@aol") <> 0 Then
233 cdoSMTPServer = "smtp.aol.com"
234 End If
235 End Property
236
237 '—————————————————————————————————————
238 ' Name: Property cdoUseSSL (Private)
239 '
240 ' Purpose: Setting for SMTP Server's use of SSL (Boolean)
241 '—————————————————————————————————————
242 Private Property Get cdoUseSSL 'As Boolean
243 '—————————————————————————————————————
244 cdoUseSSL = True
245 If InStr(1, LCase(Me.From), "@aol") <> 0 Then
246 cdoUseSSL = False
247 End If
248 End Property
249
250 '—————————————————————————————————————
251 ' Name: Property From (Public)
252 '
253 ' Purpose: Sender's Email ID
254 '—————————————————————————————————————
255 Public Property Let From( ByVal Val )
256 strFrom = Val
257 End Property
258 Public Property Get From 'As String
259 From = strFrom
260 End Property
261
262 End Class
263
264 '—————————————————————————————————————————————
265 ' Name: Sub Email (Public)
266 '
267 ' Purpose: Sends an Email Using CDO to a recipient
268 '
269 ' Parameters:
270 ' sEmailID: Sender's Mail ID String
271 ' sPassword: Sender's Password String
272 ' sTo: Recipient's Mail ID String
273 ' sSubject: Subject String
274 ' sBody: Body Message String
275 '
276 ' Return: -
277 '—————————————————————————————————————————————
278 Public Function Email( EmailID, Password, Recipient, CC, Subject, Body )
279 '—————————————————————————————————————————————
280 Set Email = New clsSendMail
281 With Email
282 .Send EmailID, Password, Recipient, CC, Subject, Body
283 End with
284 End Function
285
286 '—————————————————————————————————————————————
287 ' Name: Sub EmailFromFile (Public)
288 '
289 ' Purpose: Sends an Email Using CDO to a recipient
290 '
291 ' Parameters:
292 ' sEmailID: Sender's Mail ID String
293 ' sPassword: Sender's Password String
294 ' sTo: Recipient's Mail ID String
295 ' sSubject: Subject String
296 ' sCompleteFilePath: Text File containing the Body Message
297 '
298 ' Return: -
299 '—————————————————————————————————————————————
300 Public Function EmailFromFile( EmailID, Password, Recipient, CC, Subject, sCompleteFilePath )
301 '—————————————————————————————————————————————
302 Set EmailFromFile = New clsSendMail
303 With EmailFromFile
304 .LoadBodyMessage sCompleteFilePath
305 .Send EmailID, Password, Recipient, CC, Subject, ""
306 End with
307 End Function
use:
2
3 'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
4 Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", _
5 "", "Subject", "Hello, this is a test mail."'HTML
6
7 'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
8 Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", "", _
9 "Subject", "<h1>Hello</h1><p>Test Mail</p>"'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
10 Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", "", _
11 "Subject", "C:\MyTestMail.txt"Email "Me@MeEmail.Com", "mePassword", "You@YouEmail.Com;Them@TheirEmail.Com", _
12 "CC@YouCC.Com;CC@MeCC.Com", "Test Subject", "Test Message"
NET2.0 C#
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.Net;
9 using System.Net.Mail;
10 using System.Net.Mime;
11 //Mime is Not necerrary if you dont change the msgview and
12 //if you dont add custom/extra headers
13 using System.Threading;
14
15 namespace SendMailUsingGmail
16 {
17 public partial class Form1 : Form
18 {
19 public Form1()
20 {
21 InitializeComponent();
22 }
23
24 static bool mailSent = false;
25
26 public void SendMail()
27 {
28 //Builed The MSG
29 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
30 msg.To.Add("reciver@gmail.com");
31 msg.To.Add("another.reciver@yahoo.com");
32 msg.From = new MailAddress(dummy@gmail.com,
33 "One Ghost",System.Text.Encoding.UTF8);
34 msg.Subject = "Test mail using .net2.0";
35 msg.SubjectEncoding = System.Text.Encoding.UTF8;
36 msg.Body = "This is my msg Body";
37 msg.BodyEncoding = System.Text.Encoding.UTF8;
38 msg.IsBodyHtml = false;
39 msg.Priority = MailPriority.High;
40
41 //Add the Creddentials
42 SmtpClient client = new SmtpClient();
43 client.Credentials = new System.Net.NetworkCredential
44 ("dummy@gmail.com", "SecretPass");
45 client.Port = 587;//or use 587
46 client.Host = "smtp.gmail.com";
47 client.EnableSsl = true;
48 client.SendCompleted += new SendCompletedEventHandler
49 (client_SendCompleted);
50 object userState=msg;
51 try
52 {
53 //you can also call client.Send(msg)
54 client.SendAsync(msg, userState);
55 }
56 catch (System.Net.Mail.SmtpException ex)
57 {
58 MessageBox.Show(ex.Message, "Send Mail Error");
59 }
60 }
61
62 void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
63 {
64 MailMessage mail = (MailMessage)e.UserState;
65 string subject = mail.Subject;
66
67 if (e.Cancelled)
68 {
69 string cancelled = string.Format("[{0}] Send canceled.", subject);
70 MessageBox.Show(cancelled);
71 }
72 if (e.Error != null)
73 {
74 string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
75 MessageBox.Show(error);
76 }
77 else
78 {
79 MessageBox.Show("Message sent.");
80 }
81 mailSent = true;
82 }
83
84 private void button1_Click(object sender, EventArgs e)
85 {
86 this.SendMail();
87 }
88 }
89 }
2 //Edit some parts(UserName, password) and ENJOY!
3 public string sendMail (string from, string to, string cc,
4 string bcc, string subject, string body) {
5 // Mail initialization
6 MailMessage mailMsg = new MailMessage();
7 mailMsg.From = from;
8 mailMsg.To = to;
9 mailMsg.Cc = cc;
10 mailMsg.Bcc = bcc;
11 mailMsg.Subject = subject;
12 mailMsg.BodyFormat = MailFormat.Text;
13 mailMsg.Body = body;
14 mailMsg.Priority = MailPriority.High;
15 // Smtp configuration
16 SmtpMail.SmtpServer = "smtp.gmail.com";
17 // - smtp.gmail.com use smtp authentication
18 mailMsg.Fields.Add
19 ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
20 mailMsg.Fields.Add(http://schemas.microsoft.com/cdo/configuration/sendusername,
21 "myemail@gmail.com");
22 mailMsg.Fields.Add(http://schemas.microsoft.com/cdo/configuration/sendpassword,
23 "mypassword");
24 // - smtp.gmail.com use port 465 or 587
25 mailMsg.Fields.Add
26 (http://schemas.microsoft.com/cdo/configuration/smtpserverport, "465");
27 // - smtp.gmail.com use STARTTLS (some call this SSL)
28 mailMsg.Fields.Add
29 ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
30 // try to send Mail
31 try
32 {
33 SmtpMail.Send(mailMsg);
34 return "";
35 }
36 catch (Exception ex)
37 {
38 return ex.Message;
39 }
40 }