參考資料:[ASP.NET 3.5] 使用 Gmail 寄信, 請問下面程式錯在哪裡 ?
大學時期專題所寫到的程式碼,在此作個紀錄。
Imports System.Net
Imports System.Net.Mail
Imports System.Text.RegularExpressions
Sub Send_EMail(ByVal Recipient As String, ByVal M_Subject As String, ByVal M_Content As String, ByVal S_Account As String, ByVal S_Name As String, ByVal S_Password As String, Optional ByVal Filepath() As String = Nothing)
'Recipient收件者,M_Subject主旨,M_Content內容,'S_Account寄件人帳號,S_Name寄件人名稱,S_Password寄件人密碼,Filepath儲存在Server檔案上的路徑
'==============================================
'傳過來的寄信內容,請先處理完後再傳進M_Content變數-處理寄信內容
'==============================================
If Recipient = "" Then
Exit Sub
Else
'mail格式不符,就不送出
If Regex.IsMatch(as_to, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") = False Then
Exit Sub
End If
End If
Dim eMail As New MailMessage()
Dim attach As Attachment = Nothing
eMail.IsBodyHtml = True
'System.Net.Mail.MailAddress("寄件人的Gmail帳號@gmail.com", "寄件人名稱", System.Text.Encoding.UTF8)
eMail.From = New System.Net.Mail.MailAddress(S_Account, S_Name, System.Text.Encoding.UTF8)
eMail.SubjectEncoding = System.Text.Encoding.UTF8 '主旨編碼方式
eMail.BodyEncoding = Encoding.UTF8 '內容編碼方式
eMail.To.Add(New MailAddress(Recipient)) '收件者
eMail.Subject = M_Subject '主旨
eMail.Body = M_Content '內容
'====================================
'附加檔案
If Not Filepath Is Nothing Then
For i As Integer = 0 To Filepath.Length - 1
If Filepath(i) <> "" Then
attach = New Attachment(Filepath(i))
eMail.Attachments.Add(attach) '附加檔案
End If
Next
End If
'====================================
Dim client As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
client.Port = 587 '使用GMail,port必須使用587(25也可以),如果有其他的,例如:yahoo,hotmail等等,必須使用它們各自的port
client.Host = "smtp.gmail.com" '使用GMail,如果有其他的,例如:yahoo,hotmail等等,必須使用它們各自的host
client.EnableSsl = True '需要啟用SSL加密
client.UseDefaultCredentials = False
'client.Credentials = New System.Net.NetworkCredential("你的帳號@gmail.com", "你的gmail密碼")
client.Credentials = New System.Net.NetworkCredential(S_Account, S_Password)
client.Timeout = 500000 '建議5分鐘
client.Send(eMail)
If Not attach Is Nothing Then
attach.Dispose()
End If
eMail.Dispose()
End Sub
Step 1.然後在Button1_Click上呼叫Send_EMail並帶入參數,如下:
Send_EMail("要寄給誰的mail", "這裡是主旨", "哈囉~這裡是內容", "您的gmail帳號(例如:test@gmail.com)", "測試有限公司", "您的gmail密碼")
Step 2.最後請到您的GMail帳戶作設定,找到「安全性較低的應用程式」預設是關閉,請設定為開啟。
上述設定作完後,請測試是否成功寄信。
沒有留言:
張貼留言