@@ -63,60 +63,71 @@ MAIL_FROM_ADDRESS=info@example.com`}
63
63
مقدار فیلد <Important >MAIL_FROM_ADDRESS</Important > باید یکی از نشانیهای اضافه شده در سرویس ایمیل باشد.
64
64
</p >
65
65
</Alert >
66
+ <div className = " h-2" />
66
67
68
+ در ادامه، بایستی با اجرای دستور زیر، ماژول موردنیاز ارسال ایمیل را در پروژه خود، دانلود و نصب کنید:
69
+
70
+ <div className = " h-2" />
71
+ <div dir = ' ltr' >
72
+ <Highlight className = " bash" >
73
+ { ` dotnet add package MailKit ` }
74
+ </Highlight >
75
+ </div >
76
+ <div className = " h-2" />
67
77
68
78
در نهایت میتوانید در پروژهی خود مانند مثال زیر عمل کرده و با استفاده از دسترسی SMTP سرویس ایمیل لیارا،
69
79
اقدام به ارسال ایمیلهای تراکنشی کنید:
70
80
71
81
<div className = " h-2" />
72
82
<div dir = ' ltr' >
73
83
<Highlight className = " dotnet" >
74
- { ` using System.Net;
75
- using System.Net.Mail;
76
- using dotenv.net;
77
-
78
- DotEnv.Load(); // Load the environment variables from .env file
84
+ { ` using MailKit.Net.Smtp;
85
+ using MimeKit;
79
86
80
87
var builder = WebApplication.CreateBuilder(args);
88
+
89
+ // Load environment variables
90
+ var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email";
91
+ var smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465");
92
+ var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? "";
93
+ var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? "";
94
+ var mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "";
95
+
81
96
var app = builder.Build();
82
97
83
- app.MapGet("/send-test-email ", async context =>
98
+ app.MapGet("/", async context =>
84
99
{
85
- // Read SMTP settings from environment variables
86
- var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST");
87
- int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "587");
88
- var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER");
89
- var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD");
90
- var fromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "info@example.com";
91
- var toAddress = "recipient@example.com"; // Replace with recipient's email address
92
-
93
- // Create a new SmtpClient
94
- using (var smtpClient = new SmtpClient(smtpHost, smtpPort))
100
+ var recipientEmail = "recipient@example.com"; // Replace with recipient email
101
+
102
+ // Create the email
103
+ var email = new MimeMessage();
104
+ email.From.Add(MailboxAddress.Parse(mailFromAddress));
105
+ email.To.Add(MailboxAddress.Parse(recipientEmail));
106
+ email.Subject = "Test Email";
107
+ email.Body = new TextPart("plain")
95
108
{
96
- smtpClient.EnableSsl = true; // Use TLS encryption
97
- smtpClient.Credentials = new NetworkCredential(smtpUser, smtpPassword) ;
109
+ Text = "This is a test email sent using explicit TLS without STARTTLS."
110
+ } ;
98
111
99
- // Create the email message
100
- var mailMessage = new MailMessage(fromAddress, toAddress)
101
- {
102
- Subject = "Test Email",
103
- Body = "<h2>This is a test email sent from a .NET Core application using SMTP<h2>",
104
- IsBodyHtml = true
105
- };
106
-
107
- // Add custom headers
108
- mailMessage.Headers.Add("x-liara-tag", "test-tag");
112
+ // Add custom header
113
+ email.Headers.Add("x-liara-tag", "test-tag");
109
114
115
+ try
116
+ {
110
117
// Send the email
111
- try
112
- {
113
- await smtpClient.SendMailAsync(mailMessage);
114
- await context.Response.WriteAsync("Test email sent successfully!");
115
- }
116
- catch (Exception ex)
117
- {
118
- await context.Response.WriteAsync($"Failed to send email: {ex.Message}");
119
- }
118
+ using var client = new SmtpClient();
119
+ await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect);
120
+ await client.AuthenticateAsync(smtpUser, smtpPassword);
121
+ await client.SendAsync(email);
122
+ await client.DisconnectAsync(true);
123
+
124
+ // Respond to the client
125
+ await context.Response.WriteAsync("Email sent successfully with custom header!");
126
+ }
127
+ catch (Exception ex)
128
+ {
129
+ // Handle errors and respond to the client
130
+ await context.Response.WriteAsync($"Failed to send email: {ex.Message}");
120
131
}
121
132
});
122
133
@@ -125,69 +136,67 @@ app.Run();
125
136
</Highlight >
126
137
</div >
127
138
<div className = " h-2" />
128
- <Alert variant = ' info' >
129
- <p >
130
- با تنظیم <Important >EnableSsl = true</Important >، میتوانید بهصورت امن اقدام به ارسال ایمیلهای تراکنشی کنید.
131
- </p >
132
- </Alert >
139
+
133
140
134
141
برای استفاده از ایمیلسرور در کنترلر، میتوانید مشابه قطعه کد زیر، عمل کنید:
135
142
136
143
<div className = " h-2" />
137
144
<div dir = ' ltr' >
138
145
<Highlight className = " csharp" >
139
- { ` using MimeKit ;
140
- using MailKit.Net.Smtp ;
141
- using DotNetEnv; // for install this, run: dotnet install add package DotNetEnv
146
+ { ` using MailKit.Net.Smtp ;
147
+ using MimeKit ;
148
+ using Microsoft.AspNetCore.Mvc;
142
149
143
- namespace your_project_name.Controllers;
144
-
145
- public class TestController : Controller
150
+ namespace EmailSenderApp.Controllers
146
151
{
147
- [HttpPost]
148
- public IActionResult SendEmail(string email)
149
- {
150
- // Email Information
151
- Env.Load();
152
- string senderName = Env.GetString("SENDER_NAME");
153
- string senderEmail = Env.GetString("SENDER_ADDRESS");
154
- string subject = Env.GetString("EMAIL_SUBJECT");
155
- string body = Env.GetString("EMAIL_BODY");
156
-
157
- // Email Instance
158
- var message = new MimeMessage();
159
- message.From.Add(new MailboxAddress(senderName, senderEmail));
160
- message.To.Add(new MailboxAddress("Recipient", email));
161
- message.Subject = subject;
162
-
163
- // Creating The Body
164
- message.Body = new TextPart("plain")
152
+ [Route("api/[controller]")]
153
+ [ApiController]
154
+ public class EmailController : ControllerBase
155
+ {
156
+ // Load environment variables (or use default values)
157
+ private readonly string smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email";
158
+ private readonly int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465");
159
+ private readonly string smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? "";
160
+ private readonly string smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? "";
161
+ private readonly string mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "";
162
+
163
+ [HttpGet("send-test-email")]
164
+ public async Task<IActionResult> SendTestEmail()
165
165
{
166
- Text = body
167
- };
166
+ var recipientEmail = "recipient@example.com"; // Replace with recipient email
167
+
168
+ // Create the email
169
+ var email = new MimeMessage();
170
+ email.From.Add(MailboxAddress.Parse(mailFromAddress));
171
+ email.To.Add(MailboxAddress.Parse(recipientEmail));
172
+ email.Subject = "Test Email";
173
+ email.Body = new TextPart("plain")
174
+ {
175
+ Text = "This is a test email sent using explicit TLS without STARTTLS."
176
+ };
168
177
169
- try
170
- {
171
- // Sending Email
172
- using (var client = new SmtpClient())
178
+ // Add custom header
179
+ email.Headers.Add("x-liara-tag", "test-tag");
180
+
181
+ try
173
182
{
174
- client.Connect(Env.GetString("MAIL_HOST"), Env.GetInt("MAIL_PORT"), false);
175
- client.Authenticate(Env.GetString("MAIL_USERNAME"), Env.GetString("MAIL_PASSWORD"));
176
- client.Send(message);
177
- client.Disconnect(true);
183
+ // Send the email
184
+ using var client = new SmtpClient();
185
+ await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect);
186
+ await client.AuthenticateAsync(smtpUser, smtpPassword);
187
+ await client.SendAsync(email);
188
+ await client.DisconnectAsync(true);
189
+
190
+ // Return success response
191
+ return Ok("Email sent successfully with custom header!");
192
+ }
193
+ catch (Exception ex)
194
+ {
195
+ // Handle errors and return error response
196
+ return StatusCode(500, $"Failed to send email: {ex.Message}");
178
197
}
179
-
180
- ViewBag.Message = "Email Sent Successfully.";
181
- }
182
- catch (Exception ex)
183
- {
184
- ViewBag.Message = $"Error In Sending Email: {ex.Message}";
185
198
}
186
-
187
-
188
- return RedirectToAction("Index");
189
199
}
190
-
191
200
}
192
201
` }
193
202
</Highlight >
0 commit comments