简体   繁体   中英

PHP send mail using defined SMTP mail server

I use simple php to process sending form inputs arrays using localhost server. Now I need to switch to defined mail server like Gmail SMTP to handle sending process.

<?php

    $to = "contact@mail.com";
    $from = $_REQUEST['email'];
    $name = $_REQUEST['name'];
    $headers = "From: $from";
    $subject = "[Contact form] You have a message from $name.";

    $fields = array();
    $fields{"name"} = "Name";
    $fields{"email"} = "Email";
    $fields{"phone"} = "Phone";
    $fields{"department"} = "Department";
    $fields{"message"} = "Message";

    $body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

    $send = mail($to, $subject, $body, $headers);

?>

With mail(), you can't.

Use for example: SwiftMailer. Example:

require_once 'lib/swift_required.php';

// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
->setUsername('your username')
->setPassword('your password');

You could alternatively use a different transport such as Sendmail or Mail:

$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');

$transport = Swift_MailTransport::newInstance();

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
->setBody('Here is the message itself');

$result = $mailer->send($message);

See this: http://swiftmailer.org/docs/sending.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM