このステップバイステップガイドでは、Aspose.Email for .NETを使用してC#で電子メールを送信する方法を共有します。このC#コンソールアプリケーションではGmail SMTPサーバーを使用してメールを送信していますが、任意の種類の.NETアプリケーションで任意のSMTPサーバーを使用してメールを送信できます。
C#でメールを送信する手順
- NuGetパッケージマネージャーからAspose.Email for .NETをセットアップします
- 次の名前空間を含めます:Aspose.Email、Aspose.Email.Clients、およびAspose.Email.Clients.Smtp
- Aspose.Email.Licenseクラスを使用してライセンスを適用します
- MailMessageクラスを使用して新しいメールメッセージを作成します
- SmtpClientクラスのインスタンスを作成します
- GmailSMTPクライアント情報を設定してメールを送信する
- SmtpClientクラスのSendメソッドを使用してemailを送信します
C#を使用してメールを送信するコード
using System; | |
//Add Aspose.Email for .NET package reference | |
//Use following namespaces to convert OTG to PDF format | |
using Aspose.Email; | |
using Aspose.Email.Clients; | |
using Aspose.Email.Clients.Smtp; | |
namespace SendEmailUsingSMTPServer | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before sending email through Gmail SMTP | |
//using Aspose.Email for .NET | |
Aspose.Email.License AsposeEmailLicense = new Aspose.Email.License(); | |
AsposeEmailLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//create an instance of MailMessage | |
MailMessage EmailMessage = new MailMessage(); | |
//Set email message properties which you want to specify | |
EmailMessage.Subject = "How to Send Mail Using SMTP Server in C#"; | |
EmailMessage.To = "ReceiverEmail@EmailServer.com"; | |
EmailMessage.Body = "This is a test of sending email using SMTP in C#."; | |
//Initiate an instance of SmptpClient class | |
SmtpClient SMTPEmailClient = new SmtpClient(); | |
//Set SMTP client properties so the email message can get through the server | |
SMTPEmailClient.Host = "smtp.gmail.com"; | |
SMTPEmailClient.Username = "YourEmail@gmail.com"; | |
SMTPEmailClient.Password = "Your Gamil Password"; | |
SMTPEmailClient.Port = 587; | |
SMTPEmailClient.SecurityOptions = SecurityOptions.SSLExplicit; | |
//Finally send the email message using Gmail's SMTP client | |
SMTPEmailClient.Send(EmailMessage); | |
} | |
} | |
} |
C#でGmailSMTPを使用してメールを送信する場合の問題
「SMTPサーバーに安全な接続が必要であるか、クライアントが認証されていません。」などの例外が発生する場合があります。これは、Gmailがアプリケーションの安全性を低いと見なしているため、SMTPサーバーを使用してメールを送信できない場合があるためです。 GmailSMTPの問題を修正するにはallow access to less secure apps to send email。