📧 Epastu sūtīšana no PHP
PHP piedāvā iebūvēto mail() funkciju, bet profesionālai lietošanai ieteicams PHPMailer – plašākas iespējas, SMTP atbalsts un uzticamāka piegāde.
PHP mail() funkcija
mail() ir ātrākā metode, bet strādā tikai, ja serverim ir konfigurēts e-pasta serveris (SMTP). XAMPP vidē parasti nav konfigurēts.
⚠️ mail() ierobežojumimail() bieži tiek marķēts kā SPAM, nedz nodrošina piegādes apstiprinājumu un nav piemērots masveidīgai nosūtīšanai. Produkcijai izmantojiet PHPMailer vai līdzīgu bibliotēku.
<?php
// Pamata mail() lietošana
$saņēmējs = "jana@example.lv";
$temats = "Sveiciens no PHP!";
$ziņa = "Sveicināta, Jāna!\n\nŠis ir testepasts no PHP.\n\nAr cieņu,\nJūsu mājaslapa";
$galvenes = "From: info@example.lv\r\n";
$galvenes .= "Reply-To: navkur@example.lv\r\n";
$galvenes .= "X-Mailer: PHP/" . PHP_VERSION;
if (mail($saņēmējs, $temats, $ziņa, $galvenes)) {
echo "Epasts veiksmīgi nosūtīts!";
} else {
echo "Neizdevās nosūtīt epastu.";
}
// HTML epasts ar mail()
$html_ziņa = "
<html>
<head><meta charset='UTF-8'></head>
<body>
<h1 style='color:#2563eb;'>Sveiciens!</h1>
<p>Šis ir <strong>HTML</strong> epasts.</p>
<hr>
<p><em>Ar cieņu, PHP mājaslapa</em></p>
</body>
</html>
";
$galvenes = "MIME-Version: 1.0\r\n";
$galvenes .= "Content-type: text/html; charset=UTF-8\r\n";
$galvenes .= "From: info@example.lv\r\n";
mail($saņēmējs, "HTML Epasts", $html_ziņa, $galvenes);
?>
PHPMailer – SMTP ar autentifikāciju
PHPMailer ir vadošā PHP epastu bibliotēka. To var instalēt ar Composer vai lejupielādēt manuāli.
// Instalācija ar Composer:
// composer require phpmailer/phpmailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require "vendor/autoload.php";
$mail = new PHPMailer(true); // true = kļūdu izmešana ar Exception
try {
// ===== SMTP KONFIGURĀCIJA =====
$mail->isSMTP(); // Izmantot SMTP
$mail->Host = "smtp.gmail.com"; // SMTP serveris
$mail->SMTPAuth = true; // SMTP autentifikācija
$mail->Username = "jusu_epasts@gmail.com"; // Gmail lietotājvārds
$mail->Password = "jusu_app_password"; // Gmail App Password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL šifrēšana
$mail->Port = 465; // SSL ports
$mail->CharSet = "UTF-8";
// ===== SŪTĪTĀJS UN SAŅĒMĒJS =====
$mail->setFrom("jusu_epasts@gmail.com", "Mana Mājaslapa");
$mail->addAddress("sanemejs@example.lv", "Jānis Bērziņš"); // Saņēmējs
$mail->addCC("kopija@example.lv"); // Kopija
$mail->addBCC("slepenakopija@example.lv"); // Slepenā kopija
$mail->addReplyTo("atbildes@example.lv", "Atbildes"); // Atbildes adrese
// ===== SATURS =====
$mail->isHTML(true); // HTML formāts
$mail->Subject = "PHPMailer testa epasts 🎉";
$mail->Body = "
<html>
<body style='font-family: Arial, sans-serif; max-width: 600px;'>
<div style='background:#2563eb; padding:20px; border-radius:8px 8px 0 0;'>
<h1 style='color:white; margin:0;'>Sveiciens! 👋</h1>
</div>
<div style='padding:24px; background:#f8fafc; border:1px solid #e2e8f0;'>
<p>Labdien, <strong>Jāni</strong>!</p>
<p>Šis epasts nosūtīts ar <strong>PHPMailer</strong> un Gmail SMTP.</p>
<a href='https://example.lv'
style='display:inline-block; background:#2563eb; color:white;
padding:12px 24px; border-radius:6px; text-decoration:none;
margin-top:16px;'>
Apmeklēt lapu
</a>
</div>
</body>
</html>
";
$mail->AltBody = "Sveiciens, Jāni! Šis epasts nosūtīts ar PHPMailer.";
// ===== PIELIKUMS =====
// $mail->addAttachment("/ceļš/uz/failu.pdf", "dokuments.pdf");
$mail->send();
echo "Epasts veiksmīgi nosūtīts!";
} catch (Exception $e) {
echo "Epastu neizdevās nosūtīt. Kļūda: {$mail->ErrorInfo}";
}
?>
Populārie SMTP serveri
| Serveris | Host | Ports (SSL) | Ports (TLS) | Piezīmes |
|---|---|---|---|---|
| Gmail | smtp.gmail.com | 465 | 587 | Nepieciešams App Password |
| Outlook/Hotmail | smtp-mail.outlook.com | — | 587 | STARTTLS |
| Yahoo | smtp.mail.yahoo.com | 465 | 587 | App Password |
| Mailtrap (dev) | sandbox.smtp.mailtrap.io | — | 2525 | Tikai testēšanai! |
| SendGrid | smtp.sendgrid.net | — | 587 | API atslēga |
Gmail prasa App Password (nevis parasto paroli). Aktivizēt: Google konta iestatījumi → Drošība → 2-soļu verifikācija (ieslēgt) → App passwords → Izveidot jaunu.
Kontaktforma ar PHPMailer
Pilns piemērs – kontaktforma, kas sūta epastu ar PHPMailer:
🎓 Ko mācīties tālāk?
Pēdējā PHP sadaļā uzzināsiet, kā PHP iegūt datus no ārējiem API izmantojot cURL un file_get_contents.
<?php
// kontaktforma.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require "vendor/autoload.php";
session_start();
$kļūdas = [];
$veiksmīgi = false;
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// CSRF pārbaude
if (!hash_equals($_SESSION["csrf"] ?? "", $_POST["csrf"] ?? "")) {
die("Drošības kļūda!");
}
// Datu uztvēršana un attīrīšana
$vārds = htmlspecialchars(trim($_POST["vards"] ?? ""));
$epasts = filter_var(trim($_POST["epasts"] ?? ""), FILTER_VALIDATE_EMAIL);
$temats = htmlspecialchars(trim($_POST["temats"] ?? ""));
$ziņa = htmlspecialchars(trim($_POST["zina"] ?? ""));
// Validācija
if (empty($vārds)) $kļūdas[] = "Vārds ir obligāts.";
if (!$epasts) $kļūdas[] = "Nepareizs e-pasta formāts.";
if (strlen($ziņa) < 20) $kļūdas[] = "Ziņa pārāk īsa (min. 20 rakstzīmes).";
if (empty($kļūdas)) {
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "mana_adrese@gmail.com";
$mail->Password = "app_password";
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->CharSet = "UTF-8";
$mail->setFrom("mana_adrese@gmail.com", "Mājaslapa");
$mail->addAddress("admins@example.lv");
$mail->addReplyTo($epasts, $vārds); // Atbilde iet uz sūtītāju
$mail->isHTML(true);
$mail->Subject = "Jauna ziņa no kontaktformas: $temats";
$mail->Body = "
<h2>Jauna ziņa no kontaktformas</h2>
<table>
<tr><td><strong>Vārds:</strong></td><td>$vārds</td></tr>
<tr><td><strong>E-pasts:</strong></td><td>$epasts</td></tr>
<tr><td><strong>Temats:</strong></td><td>$temats</td></tr>
</table>
<h3>Ziņa:</h3>
<p>$ziņa</p>
";
$mail->send();
$veiksmīgi = true;
} catch (Exception $e) {
$kļūdas[] = "Neizdevās nosūtīt epastu: " . $mail->ErrorInfo;
}
}
}
// CSRF token ģenerēšana
$_SESSION["csrf"] = bin2hex(random_bytes(32));
?>
<!DOCTYPE html>
<html lang="lv">
<body>
<?php if ($veiksmīgi): ?>
<p style="color:green;">✅ Jūsu ziņa veiksmīgi nosūtīta!</p>
<?php endif; ?>
<form method="POST">
<input type="hidden" name="csrf" value="<?= $_SESSION["csrf"] ?>">
<input type="text" name="vards" placeholder="Vārds" required>
<input type="email" name="epasts" placeholder="E-pasts" required>
<input type="text" name="temats" placeholder="Temats">
<textarea name="zina" placeholder="Jūsu ziņa..."></textarea>
<button type="submit">Nosūtīt</button>
</form>
</body>
</html>