Hoe kan ik een e-mail sturen met PHP?

Ik gebruik PHP op een website en ik wil e-mailfunctionaliteit toevoegen.

Ik heb WampServergeïnstalleerd.

Hoe verstuur ik een e-mail met PHP?


Antwoord 1, autoriteit 100%

Het is mogelijk met PHP’s mail()functie. Onthoud dat de mailfunctie niet werkt op een lokaleserver.

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]'       . "\r\n" .
                 'Reply-To: [email protected]' . "\r\n" .
                 'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
?>

Referentie:


Antwoord 2, autoriteit 27%

Je kunt ook de PHPMailer-klasse gebruiken op https://github.com/PHPMailer/PHPMailer.

Hiermee kunt u de e-mailfunctie of een smtp-server transparant gebruiken. Het verwerkt ook op HTML gebaseerde e-mails en bijlagen, zodat u uw eigen implementatie niet hoeft te schrijven.

De klasse is stabiel en wordt gebruikt door veel andere projecten zoals Drupal, SugarCRM, Yii en Joomla!

Hier is een voorbeeld van de bovenstaande pagina:

<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

3, Autoriteit 10%

Als u geïnteresseerd bent in HTML-opgemaakte e-mail, moet u controleren Content-type: text/html;in de kop. Voorbeeld:

// multiple recipients
$to  = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);

Voor meer details, check de php mailfunctie.


Antwoord 4, autoriteit 4%

Kijk ook in het PEAR-mailpakket Pear Mail-pagina

Het lijkt iets robuuster dan de standaard mail()-functie die is ingebouwd (als de standaardfunctie niet adequaat is).

Hier is een fragment van deze pagina dat laat zien hoe het wordt gebruikt. PEAR Mail send()-gebruik

<?php
    include('Mail.php');
    $recipients = '[email protected]';
    $headers['From']    = '[email protected]';
    $headers['To']      = '[email protected]';
    $headers['Subject'] = 'Test message';
    $body = 'Test message';
    $smtpinfo["host"] = "smtp.server.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "smtp_user";
    $smtpinfo["password"] = "smtp_password";
    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory("smtp", $smtpinfo); 
    $mail_object->send($recipients, $headers, $body);
?> 

5, Autoriteit 3%

Voor de meeste projecten gebruik ik Swift mailer deze dagen. Het is een zeer flexibel en elegant object-georiënteerde benadering van het verzenden van e-mails, gemaakt door dezelfde mensen die gaf ons de populaire Symfony framework en Twig template engine .


Basic gebruik:

require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('[email protected]' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('[email protected]' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}

Zie de officiële documentatie voor meer informatie over het gebruik van hoe te gebruiken SWIFT MAILER.


Antwoord 6, autoriteit 2%

Probeer dit:

<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
mail($to,$subject,$txt,$headers);
?>

Antwoord 7

dit is een zeer eenvoudige methode om e-mail in platte tekst te verzenden met de e-mailfunctie.

<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);

Antwoord 8

De belangrijkste manier om e-mails vanuit PHP te verzenden, is door de ingebouwde functie mail()te gebruiken, maar er zijn een aantal kant-en-klare SDK’s die de integratie kunnen vergemakkelijken:

  1. Swiftmailer
  2. PHPMailer
  3. Pepipost(werkt via HTTP, dus problemen met SMTP-poortblokkering kunnen worden vermeden)
  4. Sendmail

P.S. Ik werk bij Pepipost.


Antwoord 9

De native PHP-functie mail()werkt niet voor mij. Het geeft het bericht:

503 Deze mailserver vereist authenticatie bij een poging om te verzenden
naar een niet-lokaal e-mailadres

Dus ik gebruik meestal het PHPMailer-pakket

Ik heb versie 5.2.23 gedownload van: GitHub.

Ik heb zojuist 2 bestanden gekozen en in mijn bron PHP-root geplaatst

class.phpmailer.php
class.smtp.php

In PHP moet het bestand worden toegevoegd

require_once('class.smtp.php');
require_once('class.phpmailer.php');

Hierna is het alleen maar code:

require_once('class.smtp.php');
require_once('class.phpmailer.php');
... 
//----------------------------------------------
// Send an e-mail. Returns true if successful 
//
//   $to - destination
//   $nameto - destination name
//   $subject - e-mail subject
//   $message - HTML e-mail body
//   altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess)  {
  $from  = "[email protected]";
  $namefrom = "yourname";
  $mail = new PHPMailer();  
  $mail->CharSet = 'UTF-8';
  $mail->isSMTP();   // by SMTP
  $mail->SMTPAuth   = true;   // user and password
  $mail->Host       = "localhost";
  $mail->Port       = 25;
  $mail->Username   = $from;  
  $mail->Password   = "yourpassword";
  $mail->SMTPSecure = "";    // options: 'ssl', 'tls' , ''  
  $mail->setFrom($from,$namefrom);   // From (origin)
  $mail->addCC($from,$namefrom);      // There is also addBCC
  $mail->Subject  = $subject;
  $mail->AltBody  = $altmess;
  $mail->Body = $message;
  $mail->isHTML();   // Set HTML type
//$mail->addAttachment("attachment");  
  $mail->addAddress($to, $nameto);
  return $mail->send();
}

het werkt als een charme


10

Voorbeeld van de volledige code ..

Probeer het eenmaal ..

<?php
// Multiple recipients
$to = '[email protected], [email protected]'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Johny</td><td>10th</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <[email protected]>, Kelly <[email protected]>';
$headers[] = 'From: Birthday Reminder <[email protected]>';
$headers[] = 'Cc: [email protected]';
$headers[] = 'Bcc: [email protected]';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>

Antwoord 11

U kunt een e-mailwebservice gebruiken zoals Postmark, Sendgrid enz.

Sendgrid versus Postmark versus Amazon SES en andere e-mail/SMTP API-providers?

Bewerken: ik gebruik nu gewoon de Google Gmail API. Ik had problemen met het verzenden van een herinneringsmail naar de organisatie van mijn werkgever vanwege strikte filters. Maar Gmail werkt zolang je mensen niet spamt.


Antwoord 12

Verzonden de e-mail met dit script

<h2>Test Mail</h2>
<?php
if (!isset($_POST["submit"]))
  {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Click To send mail">
  </form>
  <?php
  }
else
  {
  if (isset($_POST["from"]))
    {
    $from = $_POST["from"]; // sender
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $message = wordwrap($message, 70);
    mail("[email protected]",$subject,$message,"From: $from\n");
    echo "Thank you for sending an email";
    }
  }
?>

Zodra u op de knop E-mail verzenden drukt, wordt de e-mail verzonden naar [email protected]


Antwoord 13

<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";
    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);
    $to = "[email protected]";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";
    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }
    else {
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "[email protected]";
        $mail->Password = "demopassword";
        $mail->SetFrom("[email protected]", "Any demo alert");
        $mail->Subject = $subject;
        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";
        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }
}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}
?>

De bovenstaande code werkt voor mij.


Antwoord 14

                          Tested 100% Work       

Procedure voor het verzenden van een gebruikerswachtwoord via e-mail met PHPMailer:

Stap 1: Download eerst het PHPMailer-pakket van GitHub

Je kunt gewoon de PHPMailer-bronbestanden downloaden en de vereiste bestanden handmatig toevoegen.

Je kunt het ZIP-bestand met de broncode downloaden van de PHPMailer-homepage[1],
klikken op de groene knop “Klonen of downloaden” (aan de rechterkant) en vervolgens “ZIP downloaden” selecteren.
Pak het pakket uit in de map waar u de bronbestanden wilt opslaan.

[1] https://github.com/PHPMailer/PHPMailer

Stap 2: Open vervolgens (vanaf Gmail-adres) Google-account en voer de volgende stappen uit:

  1. Twee-factor wachtwoordverificatie uitschakelen in Google-account.
  2. Schakel Minder beveiliging in.
  3. App van derden toestaan.

Stap 3: Probeer onderstaande code te gebruiken (Opmerking: hier heb ik alleen de functionele code gegeven om een gebruikerswachtwoord via e-mail te verzenden met PHP en MySQL)


    <?php 
    session_start();
    use PHPMailer\PHPMailer\PHPMailer;  //add use in starting of the code
    $db = mysqli_connect('localhost', 'root', '', '[Enter your Database Name]'); // connect to database
    if (isset($_POST['forgot_btn'])) {
        forgotpassword();
    }
    function forgotpassword(){
    global $db;
        $user_id = $_POST['user_id'];
        $result = mysqli_query($db,"SELECT * FROM users where user_id='$user_id'");
        $row = mysqli_fetch_assoc($result);
        $fetch_user_id=$row['user_id'];
        $name=$row['name'];
        $email_id=$row['email_id'];
        $password=$row['password'];
        if($user_id==$fetch_user_id) {
       require '../PHPMailer/vendor/autoload.php';  //Please correctly mention the PHPMailer installed directory (Don't follow my directory)
    $mail = new PHPMailer(TRUE);
    try{
       $mail->setFrom('[Enter your From Email_Address]', '[Enter Sender Name]');
       $mail->addAddress($email_id, $name);  //[To Email Address and Name]
       $mail->Subject = 'Regarding Forgot Password';
       $mail->Body = 'Hi '.$name.',Your Login Password is:'.$password.'';
       $mail->isSMTP();
       $mail->Host = 'smtp.gmail.com';
       $mail->SMTPAuth = TRUE;
       $mail->SMTPSecure = 'tls';
       $mail->Username = '[Enter your From Email_Address]';
       $mail->Password = '[Enter your From Email_Address -> Password]';
       $mail->Port = 587;
       if($mail->send())
       {
          echo "<script>alert('Password Sent Successfully');</script>"; 
       }
       else
       {
         echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";   
       }
    }
    catch (Exception $e)
    {
       echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
    }
        }
    }
    ?>

Raadpleeg deze documenten[1] voor meer informatie:

[1]. https://alexwebdevelop.com/phpmailer-tutorial/


15

U kunt een testen doen als u het nodig hebt Doe het via tinker als de volgende code

# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('[email protected]')->subject('this works!'); });
# check your mailbox

16

e-mail met platte tekst

<?php
$to       = '[email protected]';
$subject  = 'Your email subject here';
$message  = 'Your message here';
// Carriage return type (RFC).
$eol = "\r\n";
$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/plain; charset=utf-8".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);

e-mail met html

<?php
$to       = '[email protected]';
$subject  = 'Your email subject here';
$message  = '
<html>
<head>
<title>Your '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>It is a long established fact that '.$to.' reader will be distracted by the readable content of a page when looking at its layout</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);

E-mail met bijlage

<?php
$url = "https://c.xkcd.com/random/comic/";
$ch  = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Must be set to true so that PHP follows any "Location:" header.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $a will contain all headers.
$a = curl_exec($ch);
// This is what you need, it will return you the last effective URL.
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$str  = file_get_contents($url.'info.0.json');
$json = json_decode($str, true);
// Get file info.
$imageTitle = $json['title'];
// Image url.
$imageUrl = $json['img'];
// Image alt text.
$imageAlt = $json['alt'];
// Image file.
$imageFile = file_get_contents($imageUrl);
$tokens = explode('/', $imageUrl);
// File name.
$fileName = $tokens[(count($tokens) - 1)];
// File extension.
$ext = explode(".", $fileName);
// File type.
$fileType = $ext[1];
// File size.
$header = get_headers($imageUrl, true);
$fileSize = $header['Content-Length'];
$to      = '[email protected]';
$subject = "Enjoy reading today's most interesting XKCD comics";
$message = '
<html>
<head>
<title>Your email '.$to.' is listed in our XKCD comics subscribers.</title>
</head>
<body> 
    <h1>'.$imageTitle.'</h1>
    <img src='.$imageUrl.' alt='.$imageAlt.'>
</body>
</html>';
// File.
$content = chunk_split(base64_encode($imageFile));
// A random hash will be necessary to send mixed content.
$semiRand     = md5(time());
$mimeBoundary = '==Multipart_Boundary_x{$semiRand}x';
// Carriage return type (RFC).
$eol = "\r\n";
$headers  = 'Reply-To: Name <[email protected]>'.$eol;
$headers .= 'Return-Path: Name <[email protected]>'.$eol;
$headers .= 'From: Name <[email protected]>'.$eol;
$headers .= 'Organization: Hostinger'.$eol;
$headers  = 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"{$mimeBoundary}\"".$eol;
$headers .= 'Content-Transfer-Encoding: 7bit'.$eol;
$headers .= 'X-Priority: 3'.$eol;
$headers .= 'X-Mailer: PHP'.phpversion().$eol;
// Message.
$body  = '--'.$mimeBoundary.$eol;
$body .= "Content-Type: text/html; charset=\"UTF-8\"".$eol;
$body .= 'Content-Transfer-Encoding: 7bit'.$eol;
$body .= $message.$eol;
// Attachment.
$body .= '--'.$mimeBoundary.$eol;
$body .= "Content-Type:{$fileType}; name=\"{$fileName}\"".$eol;
$body .= 'Content-Transfer-Encoding: base64'.$eol;
$body .= "Content-disposition: attachment; filename=\"{$fileName}\"".$eol;
$body .= 'X-Attachment-Id: '.rand(1000, 99999).$eol;
$body .= $content.$eol;
$body .= '--'.$mimeBoundary.'--';
$success = mail($to, $subject, $body, $headers);
if ($success === false) {
    echo '<h3>Failure</h3>';
    echo '<p>Failed to send email to '.$to.'</p>';
} else {
    echo '<p>Your email has been sent to '.$to.' successfully.</p>';
}

e-mail verificatie

<?php
function verifyLink() {
    require 'db-connection.php';
    $mysqli->select_db($dbname);
    $sql = "SELECT `email`, `hash` FROM `Users` ORDER BY `active`";
    $result = $mysqli->query($sql);
    $row = $result->fetch_row();
    if ($_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] === 'on') {
    return '<a href="https://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
    } else {
    return '<a href="http://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
    }
    $mysqli->close();
}
$to       = '[email protected]';
$subject  = 'Verify your XKCD contact email address';
$message  = '
<html>
<head>
<title>Verify '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>Please verify that you want to use '.$to.' as the contact email address for your XKCD account</p>
<p>XKCD will use this email to tell you about interesting comics updates.</p>
<div>'.verifyLink().'</div>
<h3>Do not recognise this activity?</h3>
<p>If you did not add '.$to.' to your XKCD account, ignore this email and that address will not be added to your XKCD account. Someone may have made a mistake while typing their own email address.</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);

Other episodes