如何在 C++ 中发送电子邮件

在本教程中,我们将探讨如何在 C++ 中发送 Email。您将学习如何通过简单的 API 调用在 C++ 中使用 Gmail 服务器上的 SMTP 客户端发送邮件。您无需安装 Microsoft Outlook 或任何其他电子邮件客户端即可在 Windows 和 Linux 平台中使用 API。

在 C++ 中发送电子邮件的步骤

  1. 从 NuGet 包管理器安装 Aspose.Email for C++
  2. 添加对 Aspose::Email 命名空间的引用
  3. 使用 SmtpClient Class 实例中的凭据连接到 Gmail 邮箱
  4. 使用 MailMessage 类实例从磁盘加载电子邮件消息
  5. 通过使用 SMTP 客户端公开的 Send 在 C++ 中发送电子邮件消息

您可以通过几行代码轻松使用连接到 C++ 中的 Gmail 的 SMTP 客户端发送电子邮件。在此示例中,我们展示了如何使用 SMTP 发送 EML 格式的电子邮件。您也可以发送 MSG 格式的电子邮件,并且需要在示例的 line 42 处使用 MsgLoadOption 类。

用 C++ 发送电子邮件的代码

#pragma once
#include <system/object.h>
#include <system/array.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/object_ext.h>
#include <system/exceptions.h>
#include <system/environment.h>
#include <system/diagnostics/trace.h>
#include <system/console.h>
#include <MailMessage.h>
#include <EmlLoadOptions.h>
#include <Clients/Smtp/SmtpClient/SmtpClient.h>
#pragma once
#include <Clients/SecurityOptions.h>
#include <system/io/path.h>
#include <system/io/directory_info.h>
#include <system/io/directory.h>
#include <Licensing/License.h>
using namespace Aspose::Email::Clients::Smtp;
using namespace Aspose::Email::Clients;
using namespace Aspose::Email;
using namespace System;
void SendingEMLWithSMTP()
{
// Set the license for Aspose.Email for CPP
SharedPtr<License> license = System::MakeObject<License>();
license->SetLicense(u"licFile");
// The path to the source EML file to be send
System::String dstEmail = u"Message.eml";
// Ue MailMessage class to load the email Message from disk
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>();
// Load the file in EML format
message = MailMessage::Load(dstEmail, System::MakeObject<EmlLoadOptions>());
// Instantiate SmtpClient class object to connect to SMTP server
System::SharedPtr<SmtpClient> client = System::MakeObject<SmtpClient>(u"smtp.gmail.com", 587,
u"your.email@gmail.com", u"your.password");
client->set_SecurityOptions(Aspose::Email::Clients::SecurityOptions::Auto);
try
{
// Send the message
client->Send(message);
System::Console::WriteLine(u"Message has been sent");
}
catch (System::Exception& ex)
{
System::Diagnostics::Trace::WriteLine(System::ObjectExt::ToString(ex));
}
System::Console::WriteLine(System::Environment::get_NewLine() + u"Email sent using EML file successfully. " + dstEmail);
}

之前,我们学习了 如何在 C# 中发送电子邮件。鉴于,本主题重点介绍如何使用 C++ 中的 SMTP 客户端在 Gmail 服务器上发送电子邮件。使用此示例时,您可能会收到类似 “SMTP 服务器需要安全连接或客户端未通过身份验证” 之类的异常。实际上,Gmail 怀疑您的应用程序不太安全,并禁止您使用他们的 SMTP 服务器发送电子邮件。要解决 Gmail SMTP 问题,请访问主题 allow access to less secure apps to send email

 简体中文