このチュートリアルでは、C++でEmailを送信する方法を説明します。簡単なAPI呼び出しでC++のGmailサーバーでSMTPクライアントを使用してメールを送信する方法を学習します。 WindowsおよびLinuxプラットフォームでAPIを使用するために、MicrosoftOutlookまたはその他の電子メールクライアントをインストールする必要はありません。
C++でEメールを送信する手順
- NuGetパッケージマネージャーからAspose.Email for C++をインストールします
- Aspose::Email名前空間への参照を追加します
- SmtpClient Classインスタンスのクレデンシャルを使用してGmailメールボックスに接続します
- MailMessageクラスインスタンスを使用してディスクから電子メールメッセージをロードする
- SMTPクライアントによって公開された送信を使用してC++で電子メールメッセージを送信します
数行のコードでC++でGmailに接続されたSMTPクライアントを使用してメールを簡単に送信できます。この例では、SMTPを使用してEML形式の電子メールを送信する方法を示しました。 MSG形式の電子メールメッセージを送信することもでき、例の行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にアクセスしてください。