通过梨邮件发送邮件

时间:2014-01-29 11:29:54

标签: php email ssl pear

抱歉我的英文。 我正试图通过邮件梨包发送电子邮件:

require_once "Mail.php";

$from = '<frommail@gmail.com>';
$to = '<tomail@vacant.lv>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => 'frommail@gmail.com',
        'password' => 'pass'
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}

//email addresses are changed

但结果我有错误: 无法连接到ssl://smtp.gmail.com:465 [SMTP:无法连接套接字:权限被拒绝(代码:-1,响应:) Openssl已启用。 谢谢。

1 个答案:

答案 0 :(得分:0)

在某个阶段,您可能希望发送HTML电子邮件,因此您还需要使用PEAR提供的Mail / mime包。我也把它包括在内。

<?php
require_once "Mail.php";
require_once "Mail/mime.php";

$from = "<noreply@example.com>";
$to = "fred@example.com"; // the email address
$host = "smtp.gmail.com";
$port = "587";
// use the first example username if sending from gmail, as full email address 
// is required
$username = "fred.flintstone@gmail.com";
$username = "fred";
$password = "secure";
$headers = array ('From' => $from,'To' => $to,'Subject' => $subject);
$mailbody = "<html><body>...</body></html>";

$mime = new Mail_mime();
$mime->setHTMLBody($mailbody);
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp = Mail::factory(
    'smtp',array (
        'host' => $host,
        'auth' => true,
        'username' => $username,
        'password' => $password,
        'port' => $port
    )
);

// send email
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
    echo($mail->getMessage());
} else {
    echo "<b><Center>Succesfully sent email to</b>$to</center>";
}