PHP - E-Mail senden

From XennisWiki
Jump to: navigation, search

PHP Script samt HTML 5 Formular zum Versenden von E-Mails.

<?php
    if(!empty($_POST["to"])) {
        sendMail($_POST["to"], $_POST["subject"], $_POST["message"], $_POST["from"], $_POST["toName"], $_POST["fromName"]);
    }

    /**
     * Sends a mail.
     * 
     * @param string $to          Receiver mail adress
     * @param string $subject     Subject
     * @param string $message     Message
     * @param string $from        Transmitter mail adress
     * @param string $toName      Receiver name
     * @param string $fromName    Transmitter name
     */
    function sendMail($to, $subject, $message, $from, $toName, $fromName) {

	/* To */
	if (!empty($toName)) {
            $to = $toName . ' <' . $to . '>';
	}

	/* From */
	$header = 'From: ';
	if (!empty($fromName)) {
            $header .= $fromName . ' <' . $from . '>';
	} else {
            $header .= $from;
	}
	$header .= "\r\n";


        /* Send mail */
        $result = mail($to, $subject, $message, $header);

	/* Output result */
        if ($result) {
            echo("<p>Message successfully sent!</p>");
        } else {
            echo("<p>Message delivery failed!</p>");
        }
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h2>E-Mail</h2>
        <form action="" method="post">
            <input
                type="text"
                name="fromName"
                placeholder="Your Name" />
            <input
                type="email"
                name="from"
                placeholder="From"
                required />
            <br>
            <input
                type="text"
                name="toName"
                placeholder="Receiver Name" />
            <input
                type="email"
                name="to"
                placeholder="To"
                required />
            <br>
            <input
                type="text"
                name="subject"
                placeholder="Subject" />
            <br>
            <textarea
                name="message"
                placeholder="Message"
                required></textarea>
            <br>
            <input
                type="submit"
                value="Send" />
        </form>
    </body>
</html>

External links