以下 C++ 示例代码演示如何使用 SMTP 服务器撰写和发送文本/纯文本格式的电子邮件。
EASendMail 是一个 SMTP 组件,支持 SMTP/ESMTP 协议(RFC 821、RFC 822、RFC 2554)的所有操作。在使用以下示例代码之前,您应该先下载EASendMail 安装程序并将其安装在您的机器上。
添加引用
要在您的 C++ 项目中使用 EASendMail SMTP ActiveX 对象,第一步是“将 EASendMail 的头文件添加到您的项目中”。请转到 或文件夹,找到和,然后将这些文件复制到您的项目文件夹中。
C++ - 使用 SMTP 服务器发送电子邮件 - 示例
以下示例代码演示了如何发送具有简单文本/纯文本格式的电子邮件。为了正确运行,请将、、、、值更改为您的值。
#include "stdafx.h"
#include <tchar.h>
#include <Windows.h>
#include "EASendMailObj.tlh"
using namespace EASendMailObjLib;
const int ConnectNormal = 0;
const int ConnectSSLAuto = 1;
const int ConnectSTARTTLS = 2;
const int ConnectDirectSSL = 3;
const int ConnectTryTLS = 4;
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
IMailPtr oSmtp = NULL;
oSmtp.CreateInstance(__uuidof(EASendMailObjLib::Mail));
oSmtp->LicenseCode = _T("TryIt");
// Set your sender email address
oSmtp->FromAddr = _T("test@emailarchitect.net");
// Add recipient email address
oSmtp->AddRecipientEx(_T("support@emailarchitect.net"), 0);
// Set email subject
oSmtp->Subject = _T("simple email from Visual C++ project");
// Set email body
oSmtp->BodyText = _T("this is a test email sent from Visual C++ project, do not reply");
// Your SMTP server address
oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
// User and password for ESMTP authentication, if your server doesn't
// require User authentication, please remove the following codes.
oSmtp->UserName = _T("test@emailarchitect.net");
oSmtp->Password = _T("testpassword");
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oSmtp->ConnectType = ConnectTryTLS;
// If your SMTP server uses 587 port
// oSmtp->ServerPort = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oSmtp->ServerPort = 25; // 25 or 587 or 465
// oSmtp->ConnectType = ConnectSSLAuto;
_tprintf(_T("Start to send email ...\r\n"));
if(oSmtp->SendMail() == 0)
{
_tprintf(_T("email was sent successfully!\r\n"));
}
else
{
_tprintf(_T("failed to send email with the following error: %s\r\n"),
(const TCHAR*)oSmtp->GetLastErrDescription());
}
return 0;
}
TLS 是 SSL 的后继者,现在越来越多的 SMTP 服务器需要加密。TLS 1.2
如果您的操作系统是,则需要在操作系统中启用 TLS 1.2 协议,如下所示:Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2