diff --git a/src/pages/email-server/how-tos/connect-via-platform/django.mdx b/src/pages/email-server/how-tos/connect-via-platform/django.mdx index 42e3c9d8..6a9e6700 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/django.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/django.mdx @@ -86,8 +86,8 @@ EMAIL_HOST = config('MAIL_HOST') EMAIL_PORT = config('MAIL_PORT', cast=int) EMAIL_HOST_USER = config('MAIL_USER') EMAIL_HOST_PASSWORD = config('MAIL_PASSWORD') -EMAIL_USE_TLS = False # Disable TLS -EMAIL_USE_SSL = True # Force SSL +EMAIL_USE_TLS = False # Disable STARTTLS +EMAIL_USE_SSL = True # Force TLS DEFAULT_FROM_EMAIL = f"{config('MAIL_FROM_NAME')} <{config('MAIL_FROM_ADDRESS')}>" `} diff --git a/src/pages/email-server/how-tos/connect-via-platform/dotnet.mdx b/src/pages/email-server/how-tos/connect-via-platform/dotnet.mdx index 0ff3783c..79f0f556 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/dotnet.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/dotnet.mdx @@ -63,7 +63,17 @@ MAIL_FROM_ADDRESS=info@example.com`} مقدار فیلد MAIL_FROM_ADDRESS باید یکی از نشانی‌های اضافه شده در سرویس ایمیل باشد.

+
+در ادامه، بایستی با اجرای دستور زیر، ماژول موردنیاز ارسال ایمیل را در پروژه خود، دانلود و نصب کنید: + +
+
+ + {`dotnet add package MailKit`} + +
+
در نهایت می‌توانید در پروژه‌ی خود مانند مثال زیر عمل کرده و با استفاده از دسترسی SMTP سرویس ایمیل لیارا، اقدام به ارسال ایمیل‌های تراکنشی کنید: @@ -71,52 +81,53 @@ MAIL_FROM_ADDRESS=info@example.com`}
- {`using System.Net; -using System.Net.Mail; -using dotenv.net; - -DotEnv.Load(); // Load the environment variables from .env file + {`using MailKit.Net.Smtp; +using MimeKit; var builder = WebApplication.CreateBuilder(args); + +// Load environment variables +var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email"; +var smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465"); +var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? ""; +var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? ""; +var mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? ""; + var app = builder.Build(); -app.MapGet("/send-test-email", async context => +app.MapGet("/", async context => { - // Read SMTP settings from environment variables - var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST"); - int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "587"); - var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER"); - var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD"); - var fromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "info@example.com"; - var toAddress = "recipient@example.com"; // Replace with recipient's email address - - // Create a new SmtpClient - using (var smtpClient = new SmtpClient(smtpHost, smtpPort)) + var recipientEmail = "recipient@example.com"; // Replace with recipient email + + // Create the email + var email = new MimeMessage(); + email.From.Add(MailboxAddress.Parse(mailFromAddress)); + email.To.Add(MailboxAddress.Parse(recipientEmail)); + email.Subject = "Test Email"; + email.Body = new TextPart("plain") { - smtpClient.EnableSsl = true; // Use TLS encryption - smtpClient.Credentials = new NetworkCredential(smtpUser, smtpPassword); + Text = "This is a test email sent using explicit TLS without STARTTLS." + }; - // Create the email message - var mailMessage = new MailMessage(fromAddress, toAddress) - { - Subject = "Test Email", - Body = "

This is a test email sent from a .NET Core application using SMTP

", - IsBodyHtml = true - }; - - // Add custom headers - mailMessage.Headers.Add("x-liara-tag", "test-tag"); + // Add custom header + email.Headers.Add("x-liara-tag", "test-tag"); + try + { // Send the email - try - { - await smtpClient.SendMailAsync(mailMessage); - await context.Response.WriteAsync("Test email sent successfully!"); - } - catch (Exception ex) - { - await context.Response.WriteAsync($"Failed to send email: {ex.Message}"); - } + using var client = new SmtpClient(); + await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect); + await client.AuthenticateAsync(smtpUser, smtpPassword); + await client.SendAsync(email); + await client.DisconnectAsync(true); + + // Respond to the client + await context.Response.WriteAsync("Email sent successfully with custom header!"); + } + catch (Exception ex) + { + // Handle errors and respond to the client + await context.Response.WriteAsync($"Failed to send email: {ex.Message}"); } }); @@ -125,69 +136,67 @@ app.Run();

- -

-با تنظیم EnableSsl = true، می‌توانید به‌صورت امن اقدام به ارسال ایمیل‌های تراکنشی کنید. -

-
+ برای استفاده از ایمیل‌سرور در کنترلر، می‌توانید مشابه قطعه کد زیر، عمل کنید:
- {`using MimeKit; -using MailKit.Net.Smtp; -using DotNetEnv; // for install this, run: dotnet install add package DotNetEnv + {`using MailKit.Net.Smtp; +using MimeKit; +using Microsoft.AspNetCore.Mvc; -namespace your_project_name.Controllers; - -public class TestController : Controller +namespace EmailSenderApp.Controllers { - [HttpPost] - public IActionResult SendEmail(string email) - { - // Email Information - Env.Load(); - string senderName = Env.GetString("SENDER_NAME"); - string senderEmail = Env.GetString("SENDER_ADDRESS"); - string subject = Env.GetString("EMAIL_SUBJECT"); - string body = Env.GetString("EMAIL_BODY"); - - // Email Instance - var message = new MimeMessage(); - message.From.Add(new MailboxAddress(senderName, senderEmail)); - message.To.Add(new MailboxAddress("Recipient", email)); - message.Subject = subject; - - // Creating The Body - message.Body = new TextPart("plain") + [Route("api/[controller]")] + [ApiController] + public class EmailController : ControllerBase + { + // Load environment variables (or use default values) + private readonly string smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email"; + private readonly int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465"); + private readonly string smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? ""; + private readonly string smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? ""; + private readonly string mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? ""; + + [HttpGet("send-test-email")] + public async Task SendTestEmail() { - Text = body - }; + var recipientEmail = "recipient@example.com"; // Replace with recipient email + + // Create the email + var email = new MimeMessage(); + email.From.Add(MailboxAddress.Parse(mailFromAddress)); + email.To.Add(MailboxAddress.Parse(recipientEmail)); + email.Subject = "Test Email"; + email.Body = new TextPart("plain") + { + Text = "This is a test email sent using explicit TLS without STARTTLS." + }; - try - { - // Sending Email - using (var client = new SmtpClient()) + // Add custom header + email.Headers.Add("x-liara-tag", "test-tag"); + + try { - client.Connect(Env.GetString("MAIL_HOST"), Env.GetInt("MAIL_PORT"), false); - client.Authenticate(Env.GetString("MAIL_USERNAME"), Env.GetString("MAIL_PASSWORD")); - client.Send(message); - client.Disconnect(true); + // Send the email + using var client = new SmtpClient(); + await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect); + await client.AuthenticateAsync(smtpUser, smtpPassword); + await client.SendAsync(email); + await client.DisconnectAsync(true); + + // Return success response + return Ok("Email sent successfully with custom header!"); + } + catch (Exception ex) + { + // Handle errors and return error response + return StatusCode(500, $"Failed to send email: {ex.Message}"); } - - ViewBag.Message = "Email Sent Successfully."; - } - catch (Exception ex) - { - ViewBag.Message = $"Error In Sending Email: {ex.Message}"; } - - - return RedirectToAction("Index"); } - } `} diff --git a/src/pages/email-server/how-tos/connect-via-platform/flask.mdx b/src/pages/email-server/how-tos/connect-via-platform/flask.mdx index 5720af93..ac9b66a8 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/flask.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/flask.mdx @@ -80,45 +80,46 @@ MAIL_FROM_ADDRESS=info@example.com`}
- {`from flask import Flask, request -from flask_mail import Mail, Message -from dotenv import load_dotenv + {`from flask import Flask, jsonify +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart import os -# Load environment variables from .env file -load_dotenv() - app = Flask(__name__) -# Flask-Mail configuration -app.config['MAIL_SERVER'] = os.getenv('MAIL_HOST') -app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT')) -app.config['MAIL_USERNAME'] = os.getenv('MAIL_USER') -app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD') -app.config['MAIL_USE_TLS'] = True # Use TLS for encryption -app.config['MAIL_USE_SSL'] = False # Don't use SSL, because we are using TLS -app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_FROM_ADDRESS') - -# Initialize Flask-Mail -mail = Mail(app) +# Email configuration from environment variables +MAIL_HOST = os.getenv("MAIL_HOST", "smtp.c1.liara.email") +MAIL_PORT = int(os.getenv("MAIL_PORT", 465)) +MAIL_USER = os.getenv("MAIL_USER") +MAIL_PASSWORD = os.getenv("MAIL_PASSWORD") +MAIL_FROM_ADDRESS = os.getenv("MAIL_FROM_ADDRESS") +MAIL_FROM_NAME = os.getenv("MAIL_FROM_NAME") -@app.route('/send-test-email', methods=['GET']) +@app.route("/", methods=["GET"]) def send_test_email(): try: - # Create a message - msg = Message(subject='Test Email from Flask', - recipients=['recipient@example.com'], # Replace with the recipient's email address - body='This is a test email sent from Flask using SMTP on Liara.', - extra_headers = {"x-liara-tag": "test_tag"}) # Use liara tag feature - - # Send the email - mail.send(msg) - return 'Test email sent successfully!', 200 - + # Create email message + msg = MIMEMultipart() + msg["From"] = f"{MAIL_FROM_NAME} <{MAIL_FROM_ADDRESS}>" + msg["To"] = "test@example.com" + msg["Subject"] = "Test Email" + msg["X-Liara-Tag"] = "test-tag" + + # Email body + body = "This is a test email sent with Flask and forced SSL (TLS)." + msg.attach(MIMEText(body, "plain")) + + # Connect to SMTP server using SSL + with smtplib.SMTP_SSL(MAIL_HOST, MAIL_PORT) as server: + server.login(MAIL_USER, MAIL_PASSWORD) + server.sendmail(MAIL_FROM_ADDRESS, [MAIL_FROM_ADDRESS], msg.as_string()) + + return jsonify({"message": "Test email sent successfully!"}), 200 except Exception as e: - return f'Failed to send email. Error: {str(e)}', 500 + return jsonify({"error": str(e)}), 500 -if __name__ == '__main__': +if __name__ == "__main__": app.run(debug=True) `} diff --git a/src/pages/email-server/how-tos/connect-via-platform/go.mdx b/src/pages/email-server/how-tos/connect-via-platform/go.mdx index e83b8b8d..f001a4ab 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/go.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/go.mdx @@ -88,51 +88,50 @@ MAIL_FROM=info@example.com`} {`package main import ( - "fmt" - "log" - "os" - "strconv" - - gomail "gopkg.in/gomail.v2" + "fmt" + "log" + "os" + "strconv" + gomail "gopkg.in/mail.v2" ) func main() { - - // Get environment variables for SMTP settings - mailHost := os.Getenv("MAIL_HOST") - mailPortStr := os.Getenv("MAIL_PORT") - mailUser := os.Getenv("MAIL_USER") - mailPassword := os.Getenv("MAIL_PASSWORD") - mailFrom := os.Getenv("MAIL_FROM") - - // Convert mail port from string to integer - mailPort, err := strconv.Atoi(mailPortStr) - if err != nil { - log.Fatalf("Invalid MAIL_PORT: %v", err) - } - - // Create a new email message - m := gomail.NewMessage() - m.SetHeader("From", mailFrom) - m.SetHeader("To", "recipient@example.com") // Set recipient email here - m.SetHeader("Subject", "Test Email from Go with HTML") - m.SetHeader("x-liara-tag", "test-tag") // Custom header for tagging - - // Set HTML body for the email - m.SetBody("text/html", \` -

This is a test email

-

Sent from Go using gomail and SMTP with TLS.

- \`) - - // Create SMTP dialer with TLS - d := gomail.NewDialer(mailHost, mailPort, mailUser, mailPassword) - - // Send the email - if err := d.DialAndSend(m); err != nil { - log.Fatalf("Failed to send email: %v", err) - } - - fmt.Println("Test email sent successfully!") + // Fetch environment variables + host := os.Getenv("MAIL_HOST") + + port, err := strconv.Atoi(os.Getenv("MAIL_PORT")) + if err != nil { + panic(err) + } + + user := os.Getenv("MAIL_USER") + password := os.Getenv("MAIL_PASSWORD") + from := os.Getenv("MAIL_FROM") + + // Define the email recipient, subject, and body + to := "recipient@example.com" + subject := "Test Email" + body := "This is a test email." + + // Set up the email message + msg := gomail.NewMessage() + msg.SetHeader("From", from) + msg.SetHeader("To", to) + msg.SetHeader("Subject", subject) + msg.SetHeader("x-liara-tag", "test-tag") + msg.SetBody("text/plain", body) + + // Set up the SMTP client + dialer := gomail.NewDialer(host, port, user, password) + dialer.SSL = true // force SSL + + // Send the email + err = dialer.DialAndSend(msg) + if err != nil { + log.Fatalf("Failed to send email: %s", err) + } else { + fmt.Println("Email sent successfully!") + } } `} diff --git a/src/pages/email-server/how-tos/connect-via-platform/php.mdx b/src/pages/email-server/how-tos/connect-via-platform/php.mdx index 5b4d7352..5d314c42 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/php.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/php.mdx @@ -125,7 +125,8 @@ try { $mail->Subject = 'Test Email'; $mail->Body = '

Hello from PHPMailer!

This is a test email using SMTP.

'; $mail->AltBody = 'Hello from PHPMailer! This is a test email using SMTP.'; - + $mail->addCustomHeader('x-liara-tag', 'test-tag'); // use Liara Tags + // Send the email $mail->send(); echo 'Email sent successfully!'; diff --git a/src/pages/email-server/how-tos/connect-via-platform/python.mdx b/src/pages/email-server/how-tos/connect-via-platform/python.mdx index cfac6d24..d6d59825 100644 --- a/src/pages/email-server/how-tos/connect-via-platform/python.mdx +++ b/src/pages/email-server/how-tos/connect-via-platform/python.mdx @@ -99,6 +99,7 @@ def send_email(to_address, subject, body): msg['From'] = f"{MAIL_FROM_NAME} <{MAIL_FROM_ADDRESS}>" msg['To'] = to_address msg['Subject'] = subject + msg.add_header('x-liara-tag', 'test-tag') # Add custom header msg.attach(MIMEText(body, 'plain')) # Send the email