我可以使用 swiftmailer 从我的电脑发送电子邮件,但邮件不会在服务器中发送。
我正在使用 swiftmailer 5.0.1。项目细节是,
- netbeans中的一个简单的php项目
- 快速邮件程序 5.0.1
- 树枝 1.13.1
我的代码是
public function init() {
$this->username = 'username@gmail.com';
$this->password = 'password';
$this->host = 'ssl://smtp.gmail.com';
$this->port = 465;
$this->from = 'username@gmail.com';
$this->subject = 'Company - contact';
$this->body_part_type = 'text/html';
}
public function send_email($from_name_add, $to_add, $fullname, $email, $mobile, $content) {
$this->init();
$transport = Swift_SmtpTransport::newInstance($this->host, $this->port)
->setUsername($this->username)
->setPassword($this->password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$cid = $message->embed(Swift_Image::fromPath('../public_html/pic/logo.png'));
$this->body = $this->renderEmailTemplate('email', $fullname, $email, $mobile, $content, $cid);
$message->setSubject($this->subject)
->setFrom(array('username@gmail.com' => '' . $from_name_add))
->setTo($to_add)
->setContentType($this->body_part_type)
->setBody($this->body);
$result = $mailer->send($message);
return $result;
}
这段代码在我的电脑上运行良好。但是将此代码/项目上传到服务器后,邮件未发送。错误是,
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host ssl://smtp.gmail.com [Connection timed out #110]' in /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php:259
Stack trace:
#0 /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection()
#1 /home/am***/lib/Swift/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array)
#2 /home/am***/lib/Swift/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/am***/controller/send_mail.php(54): Swift_Mailer->send(Object(Swift_Message))
#4 /home/am***/public_html/contact.php(43): send_mail->send_email('Am*** Inc', 'fe****@gma...', 'asdf', 'asdf@in.com', '111111111111', 'Testing mail')
#5 {main}
thrown in <b>/home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php</b> on line <b>259</b><br />
提示:该服务器中有一个已经在运行的 php symfony2 项目,该项目可以成功发送邮件。
这是 symfony2 代码,
$message = \Swift_Message::newInstance()
->setSubject($sub)->setFrom($from)->setTo($to)->setContentType("text/html")
->setBody($this->renderView('FZAm***Bundle:Layout:mail.html.twig', array
('name' => $this->fullname, 'mobile' => $this->mobile, 'email' => $this->email,
'content' => $this->content, 'time' => $this->sys_time, 'ip' => $userip,
'server_time' => date('Y-m-d H:i:s'))
));
try {
$this->get('mailer')->send($message);
// catch and other follows.
配置细节是,
mail_contact_from: username@gmail.com
mail_contact_to: username@gmail.com
mail_contact_sub: Contact info
我只传递了这个细节,所有设置都是默认的。如果需要任何信息,请询问我会发布。
我从 symfony2 项目更改为这个普通的 php+swift+twig 的原因是我的主机只有 100mb,我需要上传更多图片。但是symfony2占用更多的空间。