Skip to content

Commit

Permalink
docs: update mail-server/send-emails-using-platform
Browse files Browse the repository at this point in the history
  • Loading branch information
A-Najmabadi committed Dec 7, 2024
1 parent dcc33b4 commit 0a77cc9
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 85 deletions.
71 changes: 44 additions & 27 deletions src/pages/email-server/how-tos/connect-via-platform/django.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,32 @@ MAIL_FROM_ADDRESS=info@example.com`}
</p>
</Alert>

حال، بایستی قطعه کدی مشابه قطعه کد زیر را به فایل <Important>settings.py</Important> خود، اضافه کنید:
حال، بایستی ماژول مورد نیاز برنامه را با اجرای دستور زیر نصب کنید:

<div className="h-2" />
<div dir='ltr'>
<Highlight className="bash">
{`pip install decouple`}
</Highlight>
</div>
<div className="h-2" />


در ادامه، کافیست قطعه کدی مشابه قطعه کد زیر را به فایل <Important>settings.py</Important> خود، اضافه کنید:
<div className="h-2" />
<div dir='ltr'>
<Highlight className="py">
{`EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.getenv('MAIL_HOST')
EMAIL_PORT = os.getenv('MAIL_PORT')
EMAIL_HOST_USER = os.getenv('MAIL_USER')
EMAIL_HOST_PASSWORD = os.getenv('MAIL_PASSWORD')
EMAIL_USE_TLS = True # Use TLS encryption
EMAIL_FROM_ADDRESS = os.getenv('MAIL_FROM_ADDRESS')`}
{`from decouple import config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
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
DEFAULT_FROM_EMAIL = f"{config('MAIL_FROM_NAME')} <{config('MAIL_FROM_ADDRESS')}>"
`}
</Highlight>
</div>
<div className="h-2" />
Expand All @@ -86,25 +101,27 @@ EMAIL_FROM_ADDRESS = os.getenv('MAIL_FROM_ADDRESS')`}
<div dir='ltr'>
<Highlight className="py">
{`from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.conf import settings
def send_test_email(request):
subject = 'Test Email from Django'
message = 'This is a test email sent from Django using SMTP on Liara server.'
recipient_list = ['recipient@example.com']
email = EmailMessage(
subject,
message,
settings.EMAIL_FROM_ADDRESS,
recipient_list,
headers={"x-liara-tag": "test-tag"} # using liara tag feature,
)
email.send(fail_silently=False)
return HttpResponse('Test email sent successfully!') `}
from django.http import JsonResponse
def send_email(request):
subject = "Test Email"
message = "This is a test email sent using TLS."
recipient_list = ["recipient@example.com"]
headers = {"x-liara-tag": "test-tag"} # Custom headers
try:
email = EmailMessage(
subject=subject,
body=message,
from_email=None, # Uses DEFAULT_FROM_EMAIL from settings.py
to=recipient_list,
headers=headers,
)
email.send()
return JsonResponse({"status": "success", "message": "Email sent successfully!"})
except Exception as e:
return JsonResponse({"status": "error", "message": str(e)})
`}
</Highlight>
</div>
<div className="h-2" />
Expand Down
12 changes: 8 additions & 4 deletions src/pages/email-server/how-tos/connect-via-platform/laravel.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ MAIL_HOST=smtp.c1.liara.email
MAIL_PORT=587
MAIL_USERNAME=magical_benz_7s4t7p
MAIL_PASSWORD=9aaf526a-3352-4d96-99b1-63af70c696e2
MAIL_ENCRYPTION=tls
MAIL_ENCRYPTION=
MAIL_FROM_ADDRESS=info@example.com
MAIL_FROM_NAME="\${APP_NAME}"`}
</Highlight>
Expand All @@ -232,11 +232,11 @@ MAIL_FROM_NAME="\${APP_NAME}"`}
</Alert> */}


<Alert variant='info'>
{/* <Alert variant='info'>
<p>
با تنظیم <Important>MAIL_ENCRYPTION=tls</Important>، می‌توانید به‌صورت امن اقدام به ارسال ایمیل‌های تراکنشی کنید.
</p>
</Alert>
</Alert> */}
در نظر داشته باشید که باید فایل <Important>config/mail.php</Important>، شامل قطعه کد زیر، باشد:

<div className="h-2" />
Expand Down Expand Up @@ -273,6 +273,11 @@ return [
`}
</Highlight>
</div>
<Alert variant="info">
<p>
در نظر داشته باشید که Laravel برای ارسال ایمیل از رمز‌نگاری TLS استفاده می‌کند؛ در صورتی که قادر به ارسال از طریق TLS نباشد، آن را به STARTTLS، تغییر می‌دهد.
</p>
</Alert>
<div className="h-2" />

در ادامه، بایستی با اجرای دستوری مشابه دستور زیر، یک Mailable ایجاد کنید:
Expand Down Expand Up @@ -363,7 +368,6 @@ Route::get('/send-test-email', function () {

با انجام کارهای فوق، می‌توانید از ایمیل‌سرور در برنامه خود در صفحه <Important>send-test-email/</Important>، برای ارسال ایمیل، استفاده کنید.


</>
]}
/>
Expand Down
47 changes: 24 additions & 23 deletions src/pages/email-server/how-tos/connect-via-platform/php.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ import Head from "next/head";
<div className="h-2" />
<div dir='ltr'>
<Highlight className="bash">
{`composer require phpmailer/phpmailer`}
{`composer require phpmailer/phpmailer
# composer require vlucas/phpdotenv phpmailer/phpmailer # for dotenv`}
</Highlight>
</div>
<div className="h-2" />
Expand All @@ -62,8 +63,8 @@ import Head from "next/head";
<Highlight className="bash">
{`MAIL_HOST=smtp.c1.liara.email
MAIL_PORT=465
MAIL_USER=friendly_liskov_ihidh7
MAIL_PASSWORD=58455bf7-f7c9-4562-9a9e-53b051f2ba79
MAIL_USER=happy_motse_sng2rc
MAIL_PASSWORD=6e5617f9-19ab-4c93-b0ca-34ec7312c387
MAIL_FROM_ADDRESS=info@example.com
MAIL_FROM_NAME=my-app
`}
Expand Down Expand Up @@ -91,46 +92,45 @@ MAIL_FROM_NAME=my-app
<div dir='ltr'>
<Highlight className="php">
{`<?php
require 'vendor/autoload.php'; // Load Composer dependencies
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;
// Load environment variables from .env file
// Load environment variables from .env
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Create an instance of PHPMailer
// PHPMailer Configuration
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = $_ENV['MAIL_HOST'];
$mail->SMTPAuth = true;
$mail->Username = $_ENV['MAIL_USER'];
$mail->Password = $_ENV['MAIL_PASSWORD'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use TLS encryption
$mail->Port = $_ENV['MAIL_PORT'];
// Recipients
$mail->Host = $_ENV['MAIL_HOST'];
$mail->SMTPAuth = true;
$mail->Username = $_ENV['MAIL_USER'];
$mail->Password = $_ENV['MAIL_PASSWORD'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Force SMTPS (TLS encryption)
$mail->Port = $_ENV['MAIL_PORT'];
// Sender and recipient
$mail->setFrom($_ENV['MAIL_FROM_ADDRESS'], $_ENV['MAIL_FROM_NAME']);
$mail->addAddress('recipient@example.com'); // Add a recipient email
$mail->addAddress('test@example.com', 'Recipient Name');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->isHTML(true);
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer and SMTP.';
$mail->AltBody = 'This is the plain text version of the email content.';
$mail->addCustomHeader('x-liara-tag', 'test-tag'); // use Liara Tags
$mail->Body = '<h1>Hello from PHPMailer!</h1><p>This is a test email using SMTP.</p>';
$mail->AltBody = 'Hello from PHPMailer! This is a test email using SMTP.';
// Send the email
$mail->send();
echo 'Email has been sent successfully!';
echo 'Email sent successfully!';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
`}
</Highlight>
Expand All @@ -145,7 +145,8 @@ try {
<div className="h-2" />
<div dir='ltr'>
<Highlight className="bash">
{`composer require phpmailer/phpmailer`}
{`composer require phpmailer/phpmailer
# composer require vlucas/phpdotenv phpmailer/phpmailer # for dotenv`}
</Highlight>
</div>
<div className="h-2" />
Expand Down
66 changes: 35 additions & 31 deletions src/pages/email-server/how-tos/connect-via-platform/python.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -73,42 +73,46 @@ MAIL_FROM_ADDRESS=info@example.com`}
<Highlight className="python">
{`import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from ssl import create_default_context
# Read email configuration from environment variables
MAIL_HOST = os.getenv('MAIL_HOST')
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')
# 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")
def send_email(to_address, subject, body):
# Create the email message
msg = MIMEMultipart()
msg['From'] = MAIL_FROM_ADDRESS
msg['To'] = to_address
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
try:
# Connect to the SMTP server
server = smtplib.SMTP(MAIL_HOST, MAIL_PORT)
server.starttls() # Secure the connection with TLS
server.login(MAIL_USER, MAIL_PASSWORD) # Login to the SMTP server
server.send_message(msg) # Send the email
print("Email sent successfully")
# Enforce TLS
context = create_default_context()
# Connect to the server
with smtplib.SMTP_SSL(MAIL_HOST, MAIL_PORT, context=context) as server:
server.login(MAIL_USER, MAIL_PASSWORD)
# Prepare the email
msg = MIMEMultipart()
msg['From'] = f"{MAIL_FROM_NAME} <{MAIL_FROM_ADDRESS}>"
msg['To'] = to_address
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Send the email
server.sendmail(MAIL_FROM_ADDRESS, to_address, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print("Failed to send email:", e)
finally:
server.quit() # Close the connection to the server
# Send an email to the specified recipient
to_address = 'alinajmabadizadeh2002@gmail.com'
subject = 'Test Email'
body = 'This is a test email sent from Python using environment variables.'
send_email(to_address, subject, body)
print(f"Failed to send email: {e}")
# Example usage
if __name__ == "__main__":
recipient = "recipient@example.com"
subject = "Test Email"
body = "This is a test email sent from my Python app using TLS."
send_email(recipient, subject, body)
`}
</Highlight>
</div>
Expand Down Expand Up @@ -179,7 +183,7 @@ def send_email(to_address, subject, body):
server.quit() # Close the connection to the server
# Send an email to the specified recipient
to_address = 'alinajmabadizadeh2002@gmail.com'
to_address = 'recipient@example.com'
subject = 'Test Email'
body = 'This is a test email sent from Python using environment variables.'
Expand Down

0 comments on commit 0a77cc9

Please sign in to comment.