Skip to content

Commit dd8a9bb

Browse files
committed
docs: add http way to send email in all platforms
1 parent 60cfbd8 commit dd8a9bb

File tree

8 files changed

+671
-143
lines changed

8 files changed

+671
-143
lines changed

src/pages/email-server/how-tos/connect-via-platform/django.mdx

Lines changed: 124 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import Head from "next/head";
3737
</Alert>
3838

3939
<Tabs
40-
tabs={["SMTPS", "SMTP"]}
40+
tabs={["SMTPS", "SMTP", "HTTP"]}
4141
content={[
4242
<>
4343

@@ -88,7 +88,7 @@ EMAIL_HOST_USER = config('MAIL_USER')
8888
EMAIL_HOST_PASSWORD = config('MAIL_PASSWORD')
8989
EMAIL_USE_TLS = False # Disable STARTTLS
9090
EMAIL_USE_SSL = True # Force TLS
91-
DEFAULT_FROM_EMAIL = f"{config('MAIL_FROM_NAME')} <{config('MAIL_FROM_ADDRESS')}>"
91+
MAIL_FROM = f"{config('MAIL_FROM_NAME')} <{config('MAIL_FROM_ADDRESS')}>"
9292
`}
9393
</Highlight>
9494
</div>
@@ -113,7 +113,7 @@ def send_email(request):
113113
email = EmailMessage(
114114
subject=subject,
115115
body=message,
116-
from_email=None, # Uses DEFAULT_FROM_EMAIL from settings.py
116+
from_email=None, # Uses MAIL_FROM from settings.py
117117
to=recipient_list,
118118
headers=headers,
119119
)
@@ -205,7 +205,127 @@ def send_test_email(request):
205205
</div>
206206
<div className="h-2" />
207207

208-
</>
208+
</>,
209+
<>
210+
<p>
211+
برای ارسال ایمیل با استفاده از پروتکل HTTP، به <a href="/references/api/about/" className="text-[#2196f3]">API لیارا</a> و <a href="/email-server/details/mail-id" className="text-[#2196f3]">آیدی ایمیل‌سرور </a>
212+
و <a href="/email-server/how-tos/add-account" className="text-[#2196f3] ">نشانی ایمیل‌سرور</a> نیاز خواهید داشت.
213+
برای این‌کار، اطلاعات مربوطه را مشابه زیر به متغیرهای محیطی برنامه خود، اضافه کنید:
214+
215+
</p>
216+
217+
<div className="h-2" />
218+
<div dir='ltr'>
219+
<Highlight className="bash">
220+
{`MAIL_SERVER_ID=***
221+
MAIL_SERVICE_URL=https://mail-service.iran.liara.ir/api/v1/mails
222+
API_LIARA_TOKEN=***
223+
MAIL_FROM=info@example.com
224+
`}
225+
</Highlight>
226+
</div>
227+
<div className="h-2" />
228+
<Alert variant='info'>
229+
<p>
230+
مقدار فیلد <Important>MAIL_FROM_ADDRESS</Important> باید یکی از نشانی‌های اضافه شده در سرویس ایمیل باشد.
231+
</p>
232+
</Alert>
233+
234+
در ادامه، در فایل <Important>settings.py</Important> قطعه کد زیر را قرار دهید تا متغیرهای محیطی، خوانده شوند:
235+
236+
<div className="h-2" />
237+
<div dir='ltr'>
238+
<Highlight className="bash">
239+
{`import os
240+
# from dotenv import load_dotenv # Install python-dotenv package and uncomment these two lines if using .env
241+
# load_dotenv()
242+
243+
MAIL_SERVER_ID = os.getenv("MAIL_SERVER_ID")
244+
MAIL_SERVICE_URL = os.getenv("MAIL_SERVICE_URL")
245+
LIARA_API_TOKEN = os.getenv("LIARA_API_TOKEN")
246+
MAIL_FROM = os.getenv("MAIL_FROM")
247+
`}
248+
</Highlight>
249+
</div>
250+
<div className="h-2" />
251+
سپس، در app موردنظرتان، یک فایل به نام <Important>utils.py</Important> ایجاد کنید و قطعه کد زیر را در آن قرار دهید:
252+
<div className="h-2" />
253+
<div dir='ltr'>
254+
<Highlight className="python">
255+
{`import requests
256+
import os
257+
from django.conf import settings
258+
259+
def send_email(to, subject, text):
260+
url = f"{settings.MAIL_SERVICE_URL}/{settings.MAIL_SERVER_ID}/messages"
261+
262+
headers = {
263+
"Authorization": f"Bearer {settings.LIARA_API_TOKEN}",
264+
"Content-Type": "application/json",
265+
"x-liara-tag": "django_email" # Custom tag for tracking
266+
}
267+
268+
data = {
269+
"text": text,
270+
"subject": subject,
271+
"to": to,
272+
"from": settings.MAIL_FROM,
273+
"attachments": []
274+
}
275+
276+
try:
277+
response = requests.post(url, json=data, headers=headers)
278+
response.raise_for_status() # Raises an error for HTTP errors
279+
return response.json()
280+
except requests.exceptions.RequestException as e:
281+
return {"error": str(e)}
282+
`}
283+
</Highlight>
284+
</div>
285+
<div className="h-2" />
286+
287+
در ادامه، در فایل <Important>views.py</Important> قطعه کد زیر را قرار دهید (یا به آن اضافه کنید):
288+
289+
<div className="h-2" />
290+
<div dir='ltr'>
291+
<Highlight className="python">
292+
{`from django.http import JsonResponse
293+
from .utils import send_email
294+
295+
def send_test_email(request):
296+
response = send_email("receiver@example.com", "Test Email from Django", "This is a test email from Django using Liara Mail Service.")
297+
return JsonResponse(response)
298+
`}
299+
</Highlight>
300+
</div>
301+
<div className="h-2" />
302+
در نهایت، در فایل <Important>urls.py</Important>، مسیری برای این view ایجاد کنید:
303+
304+
<div className="h-2" />
305+
<div dir='ltr'>
306+
<Highlight className="python">
307+
{`
308+
from <your-app-name>.views import send_test_email
309+
310+
urlpatterns = [
311+
path('send-email/', send_test_email, name='send_email'),
312+
]
313+
`}
314+
</Highlight>
315+
</div>
316+
<div className="h-2" />
317+
<p>
318+
اکنون می‌توانید پس از اجرای برنامه و با اجرای دستور زیر، اقدام به ارسال ایمیل بفرمایید:
319+
320+
</p>
321+
<div className="h-2" />
322+
<div dir='ltr'>
323+
<Highlight className="bash">
324+
{`curl http://127.0.0.1:8000/send-email/`}
325+
</Highlight>
326+
</div>
327+
<div className="h-2" />
328+
</>,
209329
]}
210330
/>
211331

src/pages/email-server/how-tos/connect-via-platform/dotnet.mdx

Lines changed: 141 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import Head from "next/head";
3737
</Alert>
3838

3939
<Tabs
40-
tabs={["SMTPS", "SMTP"]}
40+
tabs={["SMTPS", "SMTP", "HTTP"]}
4141
content={[
4242
<>
4343

@@ -357,7 +357,146 @@ public class TestController : Controller
357357
</Highlight>
358358
</div>
359359
<div className="h-2" />
360-
</>
360+
</>,
361+
<>
362+
<p>
363+
برای ارسال ایمیل با استفاده از پروتکل HTTP، به <a href="/references/api/about/" className="text-[#2196f3]">API لیارا</a> و <a href="/email-server/details/mail-id" className="text-[#2196f3]">آیدی ایمیل‌سرور </a>
364+
و <a href="/email-server/how-tos/add-account" className="text-[#2196f3] ">نشانی ایمیل‌سرور</a> نیاز خواهید داشت.
365+
برای این‌کار، اطلاعات مربوطه را مشابه زیر در فایل <Important>appsettings.json</Important> قرار دهید:
366+
367+
</p>
368+
369+
<div className="h-2" />
370+
<div dir='ltr'>
371+
<Highlight className="json">
372+
{`{
373+
"LiaraMail": {
374+
"MailServerId": "66efbaf4b153ef13b8807347",
375+
"MailServiceUrl": "https://mail-service.iran.liara.ir/api/v1/mails",
376+
"LIARA_API_TOKEN": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiI2NGU3NDRjYmIxYWM3OTcyYTZlMGM3ZTQiLCJ0eXBlIjoiYXV0aCIsImlhdCI6MTczMTQwNTIwM30.ynfNoJcmOiY1Ie9eGu4frGbyTihdYLfsx5tumVdbIOI",
377+
"MAIL_FROM": "contact@looms.ir"
378+
}
379+
}
380+
`}
381+
</Highlight>
382+
</div>
383+
<div className="h-2" />
384+
<Alert variant='info'>
385+
<p>
386+
مقدار فیلد <Important>MAIL_FROM_EMAIL</Important> باید یکی از نشانی‌های اضافه شده در سرویس ایمیل باشد.
387+
</p>
388+
</Alert>
389+
<div className="h-2" />
390+
391+
در ادامه، باید پکیج‌های زیر را برای ارسال ایمیل، نصب کنید:
392+
393+
<div className="h-2" />
394+
<div dir='ltr'>
395+
<Highlight className="bash">
396+
{`dotnet add package System.Net.Http.Json
397+
dotnet add package Microsoft.Extensions.Configuration.Json
398+
`}
399+
</Highlight>
400+
</div>
401+
<div className="h-2" />
402+
403+
سپس، در مسیر اصلی پروژه، یک فایل به نام <Important>EmailService.cs</Important> ایجاد کنید و قطعه کد زیر را درون آن قرار دهید:
404+
405+
406+
<div className="h-2" />
407+
<div dir='ltr'>
408+
<Highlight className="bash">
409+
{`using System;
410+
using System.Net.Http;
411+
using System.Net.Http.Json;
412+
using System.Text.Json;
413+
using Microsoft.Extensions.Configuration;
414+
using System.Threading.Tasks;
415+
416+
public class EmailService
417+
{
418+
private readonly HttpClient _httpClient;
419+
private readonly string _mailServerId;
420+
private readonly string _mailServiceUrl;
421+
private readonly string _liaraApiToken;
422+
private readonly string _mail_from;
423+
424+
public EmailService()
425+
{
426+
// Load configuration from appsettings.json
427+
var config = new ConfigurationBuilder()
428+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
429+
.Build();
430+
431+
var mailSettings = config.GetSection("LiaraMail");
432+
_mailServerId = mailSettings["MailServerId"];
433+
_mailServiceUrl = mailSettings["MailServiceUrl"];
434+
_liaraApiToken = mailSettings["LIARA_API_TOKEN"];
435+
_mail_from = mailSettings["MAIL_FROM"];
436+
437+
_httpClient = new HttpClient();
438+
}
439+
440+
public async Task SendEmailAsync(string to, string subject, string text)
441+
{
442+
var url = $"{_mailServiceUrl}/{_mailServerId}/messages";
443+
444+
var request = new
445+
{
446+
text = text,
447+
subject = subject,
448+
to = to,
449+
from = _MAIL_FROM,
450+
attachments = new object[] { }
451+
};
452+
453+
var requestMessage = new HttpRequestMessage(HttpMethod.Post, url)
454+
{
455+
Content = JsonContent.Create(request)
456+
};
457+
458+
requestMessage.Headers.Add("Authorization", $"Bearer {_liaraApiToken}");
459+
requestMessage.Headers.Add("x-liara-tag", "dotnet_email"); // Custom tag
460+
461+
try
462+
{
463+
var response = await _httpClient.SendAsync(requestMessage);
464+
response.EnsureSuccessStatusCode();
465+
Console.WriteLine("Email sent successfully!");
466+
}
467+
catch (Exception ex)
468+
{
469+
Console.WriteLine($"Error sending email: {ex.Message}");
470+
}
471+
}
472+
}
473+
`}
474+
</Highlight>
475+
</div>
476+
<div className="h-2" />
477+
478+
در نهایت، قطعه کد زیر را در فایل <Important>Program.cs</Important> قرار دهید و بعد از آن، می‌توانید اقدام به ارسال ایمیل، بفرمایید:
479+
480+
481+
<div className="h-2" />
482+
<div dir='ltr'>
483+
<Highlight className="bash">
484+
{`using System;
485+
using System.Threading.Tasks;
486+
487+
class Program
488+
{
489+
static async Task Main()
490+
{
491+
var emailService = new EmailService();
492+
await emailService.SendEmailAsync("receiver@example.com", "Hello from .NET", "Testing Liara Mail Service in .NET!");
493+
}
494+
}
495+
`}
496+
</Highlight>
497+
</div>
498+
<div className="h-2" />
499+
</>,
361500
]}
362501
/>
363502

0 commit comments

Comments
 (0)