Use PHP mail to send via smtp

2019-02-25 16:04发布

Does anybody know if you can configure php's mail() command so it will only use an SMTP server rather than the local sendmail? We are having trouble with emails being marked as spam.

Our server is running RedHat 5 Enterprise.

I am aware of various PHP libraries that act as an SMTP client but I'd rather configure PHP so mail() used an SMTP server directly.

标签: php email rhel
5条回答
Fickle 薄情
2楼-- · 2019-02-25 16:35

No, the reason is that all Linux/Unix systems should have a "sendmail" tool. The benefit there is that this external tool can handle timeouts or unresponsive SMTP servers so it becomes more likely the mail is being really sent. The SMTP client implementation for Windows is a work-around for the fact that "sendmail" doesn't exist there.

My approach would be to use a sendmail-compatible tool that just talks to another server using SMTP. A simple tool for that is ssmtp (sources avialable here)

查看更多
一夜七次
3楼-- · 2019-02-25 16:39

Check these links:

Example:

Update: You can use this then, but it opens and closes the SMTP socket on each mail() function called.

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>
查看更多
Melony?
4楼-- · 2019-02-25 16:44

According to this manual page, it is possible on Windows only.

查看更多
走好不送
5楼-- · 2019-02-25 16:57

Just configure your local sendmail to use your upstream mail server as a relay! That way, you don't have to change anything on the PHP side.

It would not be a good idea to send mail directly from PHP with SMTP, because you would lose everything from error handling to queueing this way!

查看更多
乱世女痞
6楼-- · 2019-02-25 16:57

You can send via SMTP directly using the PEAR Mail package. You'll also need Net_SMTP installed for SMTP mail to work. On many servers, these are installed by default. You can also download a copy of these libraries locally and upload them to your site's directory or include path. That's not as ideal a solution, but it's functional.

If you're looking for a drop-in replacement for your old mail() function but which sends through SMTP instead of the PHP default, you'll need to write a translator function which sets all the parameters in the right order and such. There's an example here of just such a script -- obviously you'll have to modify it to match the settings you want: http://tltech.com/info/php-mail-via-smtp/

查看更多
登录 后发表回答