Mail sending php
Here is a basic example of how to send an email using PHP:
Using the mail()
function
<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email sent using PHP';
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: text/plain; charset=UTF-8';
if (mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
Using a PHPMailer class
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email sent using PHPMailer';
if ($mail->send()) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
Using SwiftMailer
<?php
require 'SwiftMailer/Swift.php';
$mail = new Swift_Mailer();
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email sent using SwiftMailer';
if ($mail->send()) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
Common issues and solutions
- Email not being sent: Check that your email server is configured correctly and that you have the correct credentials.
- Email being sent but not received: Check that the recipient's email server is not blocking your emails.
- Error messages: Check the error logs to see if there are any error messages that can help you diagnose the issue.
Security considerations
- Use a secure connection: Use a secure connection (TLS or SSL) when sending emails to prevent eavesdropping and tampering.
- Validate user input: Validate any user input that is used in the email content to prevent injection attacks.
- Use a reputable email library: Use a reputable email library such as PHPMailer or SwiftMailer to ensure that your emails are sent securely and correctly.