VBA自帶的語法可以處理Outlook郵箱,但是缺點是outlook還需要配置,
但是調用系統自帶的CDO接口可以用SMTP模式發送各大第三方的郵箱,只需要開啟POP3/SMTP模式即可,兼容性更好.
Sub CDOSENDEMAIL()
'On Error Resume Next '出錯后繼續執行
Application.DisplayAlerts = False '禁用系統提示
'ThisWorkbook.ChangeFileAccess Mode:=xlReadOnly '將工作簿設置為只讀模式
Set CDOMail = CreateObject("CDO.Message") '創建對象
CDOMail.From = "sender@sina.com" '設置發信人的郵箱
CDOMail.To = "receiver@qq.com" '設置收信人的郵箱
CDOMail.Subject = "主題:用CDO發送郵件試驗" '設定郵件的主題
CDOMail.TextBody = "文本內容" '使用文本格式發送郵件似乎不能換行,只能切換成HTML模式換行."
CDOMail.HtmlBody = "使用html" & "<br>" & "換行后的內容" '使用Html格式發送郵件
'CDOMail.AddAttachment ThisWorkbook.Path & "\" & "a" & ".xlsx" '發送當前目錄下的工作簿a為附件
stUl = "http://schemas.microsoft.com/cdo/configuration/" '微軟服務器網址
'stUl = "http://pop.sina.com" '微軟服務器網址
With CDOMail.Configuration.Fields
'.Item(stUl & "smtpusessl") = True
.Item(stUl & "smtpserver") = "smtp.sina.com" 'SMTP服務器地址
.Item(stUl & "smtpserverport") = 25 'SMTP服務器端口 465 是ssl連接 25是普通連接
.Item(stUl & "sendusing") = 2 '發送端口
.Item(stUl & "smtpauthenticate") = 1 '遠程服務器需要驗證
.Item(stUl & "sendusername") = "sxfxtf@sina.com" '發送方郵箱名稱
.Item(stUl & "sendpassword") = "授權碼" '上面連接生成的授權碼,非你qq郵箱密碼
.Item(stUl & "smtpconnectiontimeout") = 60 '連接超時(秒)
.Update
End With
CDOMail.Send '執行發送
Set CDOMail = Nothing '發送成功后即時釋放對象
'If Err.Number = 0 Then
'MsgBox "成功發送郵件", , "溫馨提示" '如果沒有出錯,則提示發送成功
'Else
'MsgBox Err.Description, vbInformation, "郵件發送失敗" '如果出錯,則提示錯誤類型和錯誤代碼
'End If
'ThisWorkbook.ChangeFileAccess Mode:=xlReadWrite '將工作簿設置為讀寫模式
'Kill ThisWorkbook.Path & "\" & "a" & ".xlsx" '新工作簿刪除
'Call dayin
Application.DisplayAlerts = True '恢復系統提示
End Sub