How can PHP be used to send and receive emails from a web server?
To send and receive emails from a web server using PHP, you can use the built-in `mail()` function to send emails and the `IMAP` or `POP3` extensions to receive emails. You will need to configure your server to allow outgoing and incoming email connections, and ensure that the necessary PHP extensions are enabled.
// Sending an email
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
mail($to, $subject, $message, $headers);
// Receiving emails
$hostname = '{mail.example.com:993/imap/ssl}INBOX';
$username = 'email@example.com';
$password = 'password';
$mailbox = imap_open($hostname, $username, $password);
if ($mailbox) {
$emails = imap_search($mailbox, 'ALL');
if ($emails) {
foreach ($emails as $email_number) {
$email_header = imap_headerinfo($mailbox, $email_number);
echo "From: " . $email_header->fromaddress . "<br>";
echo "Subject: " . $email_header->subject . "<br>";
}
}
imap_close($mailbox);
}