Sending email using Zend Framework and PHP - php

I working on a form whereby when the user enter in their email account and click on send, an email will be sent to their email account.
I have everything worked out. Just that it doesnt send the email to my account. Anyone have any ideas? Is there a configuration that I left out or something?
This is the sample from my controller:
public function retrieveemailAction(){
$users = new Users();
$email = $_POST['email'];
$view = Zend_Registry::get('view');
if($users->checkEmail($_POST['email'])) {
// The Subject
$subject = "Email Test";
// The message
$message = "this is a test";
// Send email
// Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
// Use if command to display email message status
if(mail($email, $subject, $message, $headers)) {
$view->operation = 'true';
}
} else {
$view->operation = 'false';
}
$view->render('retrieve.tpl');
}

I recommend you use Zend_Mail instead of mail(). It handles a lot of stuff automatically and just works great.
Do you have a SMTP server? Trying to send mail without your own SMTP server could be causing the mail to not be sent.
This is what I use for sending mails using Zend_Mail and Gmail:
In Bootstrap.php, I configure a default mail transport:
protected function _initMail()
{
try {
$config = array(
'auth' => 'login',
'username' => 'username#gmail.com',
'password' => 'password',
'ssl' => 'tls',
'port' => 587
);
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($mailTransport);
} catch (Zend_Exception $e){
//Do something with exception
}
}
Then to send an email I use the following code:
//Prepare email
$mail = new Zend_Mail();
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setBody($message);
$mail->setFrom('username#gmail.com', 'User Name');
//Send it!
$sent = true;
try {
$mail->send();
} catch (Exception $e){
$sent = false;
}
//Do stuff (display error message, log it, redirect user, etc)
if($sent){
//Mail was sent successfully.
} else {
//Mail failed to send.
}

First of all i would switch to using Zend_Mail. Second i would use a real mail account on an smtp server somewhere and send from that. A lot of times there are restrictions on sending from the server itself, but using an actual mail server usually fixes this.

There's a very useful screencast covering Zend_Mail available on ZendCasts
http://www.zendcasts.com/introduction-to-zend_mail/2010/02/

In line $mail->setBody($message);, change it to $mail->setBodyText($message);

Related

email sent successfully but no email received and not in spam using swiftmailer

I am using Swiftmailer. Though mail is received in local successfully but it doesn't work in live though message is 'mail sent successfully'.
Code:
require_once APPPATH.'swiftmailer/swift_required.php';
try {
$transport = Swift_MailTransport::newInstance();
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance($email_subject)
->setFrom(array('xxx#yyy.org' => 'xxx'))
->setTo(array('abc#gmail.com' => ''))
->setBody($email_message, 'text/html');
// Send the message
$result = $mailer->send($message);
$message = array('type' => 'success', 'message' => 'Email Sent successfully.');
} catch(Exception $e) {
echo '<pre>'; echo $e; die;
$message = array('type' => 'danger', 'message' => $e);
}
Any help/suggestion are welcome.
Email sent successfully shows because the the functionality of the php is to deliver the mail to the mail server running as per your configuration in your php.ini file. It is the job of the mail server to send mail or not. If your mail server is not configured properly then mail will not be sent but it will be shown as successful because mail function delivered the mail to the server, now it is the job of mail server to send mail or not. So check the log of your mail server.

PHPMailer DSN How to get error when address not exist

I use PHPMailer for PHP5/6 and i try to make script witch will send mail and get error like "550 No Such User Here".
I read about DSN, and try tips from this How to set DSN (Delivery Status Notification) for PHPMailer? topic, but it's doesnt work.
(i found functin recipient where was
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $toaddr . '>',
array(250, 251)
);
)
and i try change link
'RCPT TO:<' . $toaddr . '>',
to
'RCPT TO:<' . $toaddr . '> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;' . $toaddr ."" .self::CRLF,
but i doesnt work.
I was try add it by function AddCustomHeader but it fail too.
This is my code:
private function send($username, $password, $from, $nameFrom, $replay, $subject, $email) {
try {
$_ = Zend_Registry::get('Zend_Translate');
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPKeepAlive = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->SetFrom($from, $nameFrom);
$mail->AddReplyTo($replay, $nameFrom);
$mail->Subject = $subject;
$mail->MsgHTML($this->_content);
$mail->AddAddress($email);
// $mail->AddCustomHeader( "X-Confirm-Reading-To: development.tabi#gmail.com" );
// $mail->AddCustomHeader( "NOTIFY=SUCCESS,FAILURE ORCPT=rfc822; $email" );
// $mail->AddCustomHeader( "Disposition-Notification-To: development.tabi#gmail.com" );
// $mail->AddCustomHeader( "Return-receipt-to: development.tabi#gmail.com" );
if (!$mail->Send()) {
return array(
'status' => false,
'message' => $mail->ErrorInfo
);
} else {
return array(
'status' => true,
'message' => $_->_('__MAIL_WAS_SEND__')
);
}
} catch (Exception $e) {
return array(
'status' => false,
'message' => $e->getMessage()
);
}
catch (phpmailerException $e) {
return array(
'status' => false,
'message' => $e->getMessage()
);
}
}
In result i have need script where:
When i write real address, ex my_real_addres#gmail.com it will be send,
but when i write fake address, ex my_fake_addres_which_not_exist#gmail.com will return me code 550, or any other error.
Is there any options to do this ? becouse i need to get and save all information.
Remember, that due to spambots and e-mail verifying scripts (such as yours). Many mail servers do not send those responses.
If they did, they would be flooded by spambots that would be asking for whole their mail databases (millions of records) if those e-mails exist.
For that reason, it's disabled on most mailservers nowdays.
Sources:
Is there a way to test if an E-Mail address exists without sending a test mail?
How to check if an email address exists without sending an email?
Edit:
Basically, every of those functions can be disabled by server admin. They may even return faked info etc. It's all to make it unsusable to spammers (legit uses got to suffer from this).
There are other methods to verify if e-mail exists. Ask for reply, for delivery confirmation etc.
Some servers when message could not be delivered return you e-mail. But that's not 100% sure behaviour, since spammers could spam servers with random generated e-mails and wait for returns.
Those measures are implemented to pervent spammers with brute-force mass e-mail checks.
They could run dictionary attack against google servers and quickly create list of all existing emails.
Don't know what you want achive, if you want to check if one of your newsletter subscribers deleted e-mail or grabbed e-mail from random site and want to confirm it.
You should follow one principle: All e-mails are unverified by default. You never know if its real or not unless it's been verified by recipent by clicking link, answering etc.
By me, there should be no status as "100% does not exist" since you're unable to verify it.

PHP error when trying to send email using Swift Mailer

I ve tried everything, i don't know how to fix this, so, i am using this Swift Mailer library to send a confirmation email. So here is the code from my index.php
if($confirm){
//include the swift class
include_once 'inc/php/swift/swift_required.php';
//put info into an array to send to the function
$info = array(
'username' => $username,
'email' => $email,
'key' => $key);
//send the email
if(send_email($info)){
//email sent
$action['result'] = 'success';
array_push($text,'Thanks for signing up. Please check your email for confirmation!');
}else{
$action['result'] = 'error';
array_push($text,'Could not send confirm email');
}
}
And my send_email function is in another php file functions.php
//send the welcome letter
function send_email($info){
//format each email
$body = format_email($info,'html');
$body_plain_txt = format_email($info,'txt');
//setup the mailer
$transport = Swift_MailTransport::newInstance(smtp.gmail.com,465,ssl)
->setUsername('my email here')
->setPassword('my password');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message ->setSubject('Welcome to Site Name');
$message ->setFrom(array('somedomain.com' => 'somethinghere'));
$message ->setTo(array($info['email'] => $info['username']));
$message ->setBody($body_plain_txt);
$message ->addPart($body, 'text/html');
$result = $mailer->send($message);
return $result;
}
The error that i am getting is
Fatal error: Call to undefined method Swift_MailTransport::setUsername() in /srv/disk7/something/www/something/signup/inc/php/functions.php on line 31
How can i fix this? I am a beginner in php.
I'm guessing Swift_MailTransport::newInstance(smtp.gmail.com,465,ssl) fails to create the expected instance.
BTW, shouldn't it be Swift_MailTransport::newInstance('smtp.gmail.com',465,'ssl') (i.e. smtp.gmail.com and ssl in quotes)?
Swift_MailTransport, from the documentation...
...sends messages by delegating to PHP's internal mail() function.
In my experience -- and others' -- the mail() function is not particularly predictable, or helpful.
Another thing it does not have is a setUsername or setPassword method.
I'd say you want to use Swift_SmtpTransport
One more thing; as pointed out by others, your string arguments should be quoted, ie
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl');
Looks like you haven't included the Swift Mail class.

Sending an email verification after registering

I want, that users who register on my site, have to activate their account first, before using it. The problem is, that I don't get any email to my email test account.
Before I start posting a code, could the problem be, that I'm working currently on a local machine with xampp?
Otherwise, here is the code snippet
$random = substr(number_format(time() * rand(),0,'',''),0,10);
$insertMailVerify = $this->db->prepare("INSERT INTO mailverify (mailAddress, token, datetime) VALUES (:mailAddress, :token, :date)");
$insertMailVerify->execute(array(':mailAddress'=>$emailAddress,
':token'=>$random,
':date'=>$date));
$to = $emailAddress;
$subject = "Activating your Account";
$body = "Hi, in order to activate your account please visit http://localhost/FinalYear/activation.php?email=".$emailAddress." and fill in the verification code $random";
if(mail($to, $subject, $body))
{
echo ("<p>Message success</p>");
}
else {
echo ("<p>Message fail</p>");
}
Just in case you wonder where i take $emailAddress from: This is just a code snippet, i already let the software echo the email address, and it's correct. It even goes in the "Message success" if case, but I still can't get any email. What could be the problem?
After submit the form you can use a code or link and send it to the user email id
$message = "Your Activation Code is ".$code."";
$to=$email;
$subject="Activation Code For Talkerscode.com";
$from = 'your email';
$body='Your Activation Code is '.$code.' Please Click On This link Verify.php?id='.$db_id.'&code='.$code.'to activate your account.';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
echo "An Activation Code Is Sent To You Check You Emails";
Code from TalkersCode.com for complete tutorial visit http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php
in local host i think the best way is using phpmailer and gmail account
here the tutorial : http://www.web-development-blog.com/archives/send-e-mail-messages-via-smtp-with-phpmailer-and-gmail/
It seems your mail server SMTP is not configured correctly....
check the port and IP of SMTP server address.
Try to change you PHP.ini file like this and tell me if it works.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
; http://php.net/smtp-port
smtp_port = 465 //if 465 is not working then try 25
If this is not working then there are a lot of tutorials of how to achieve what you are trying to do.
Here is one link: Send email from localhost
Had the same problem, but on linux.
1) Assuming your mail() function is working properly: the problem could be, that email is coming into spam-box (because these localhost mail systems are often marked as spambots, so email services are protecting emails from unverified host).
2) If mail() is not working, its not configured properly, if you follow some tutorial and configure it, which needs like 5 minutes, you will realise why not to use it:)
The best way for you is to use some free or paid smtp service. Very easy, quick and your emails wont be marked as spam. And install PEAR library to send email. Here is an example.
$from = 'from#domain.com';
$to = 'to#domain.com';
$subject = 'subject';
$body = 'Hello!';
$host = 'smtpserver.com';
$port = '25';
$username = 'yourlogin';
$password = 'yourpass';
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if(PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
To your verification code: instead of telling user to write down the verification code, better generate him the link, that he clicks his account gets activated. Something like
http://localhost/FinalYear/activation.php?email=some#email.com&token=79054025255fb1a26e4bc422aef54eb4
on registration page: generate the activation token like md5($email . '_sometext');
on activation page if(md5($_GET['email'] . '_sometext') == $_GET['token']) { activate.. }
please note, that it is just an example, there are 10 ways how it could be done :)

How to instantiate mail() function and send an email with Joomla2.5?

Based on the Joomla! documentation # http://docs.joomla.org/Sending_email_from_extensions, I'm trying to send emails with the code below:
function sendmail($file,$mailto)
{
$mailer =& JFactory::getMailer();
//var_dump($mailer); exit;
$config =&JFactory::getConfig();
$sender = array(
$config->getValue( 'config.mailfrom' ),
$config->getValue( 'config.fromname' )
);
$mailer->setSender($sender);
$recipient = array($mailto);
$mailer->addRecipient($recipient);
$body = "Your body string\nin double quotes if you want to parse the \nnewlines etc";
$mailer->setSubject('Your subject string');
$mailer->setBody($body);
// Optional file attached
$mailer->addAttachment(JPATH_BASE.DS.'CSV'.DS.$file);
$send =&$mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->message;
} else {
echo 'Mail sent';
}
}
($file is the full path of a file zip and $mailto is a my gmail.)
However, when I send mail, I receive the error:
Could not instantiate mail function.
Fatal error: Cannot access protected property JException::$message in /var/www/html/dai/components/com_servicemanager/views/i0602/view.html.php on line 142
What is causing this error?
Please save yourself some sanity and do not try to use Joomla's mailer implementation. Not only is it unreliable as you've experienced, it handles different charsets and HTML content poorly. Just include and use PHPMailer.
Change
echo 'Error sending email: ' . $send->message;
to
echo 'Error sending email:'.$send->get('message');
then run your code again. The error that you get should tell us why it isn't instantiating.
In joomla send a mail with attachment file
$from="noreplay#gmail.com";//Please set Proper email id
$fromname="noreplay";
$to ='admin#gmail.com';
// Set a you want send email to
$subject = "Download";
$message = "Thank you For Downloading";
$attachment = JPATH_BASE.'/media/demo.pdf';
// set a file path
$res = JFactory::getMailer()->sendMail($from, $fromname, $to,$subject, $message,$mode=1,$cc = null, $bcc = null, $attachment);
if($res)
{
$errormsg = "Mail Successfully Send";
}
else
{
$errormsg ="Mail Not Send";
}
after you have check mail in your inbox or spam folder.
mail in spam folder because not proper set email id in from id.
After several years of Joomla development, I recommend using RSFORM PRO by RSJOOMLA to send mail for you after the visitor to your website fills out the form. It is much easier to manage than having to deal with the internal mail server.

Categories