I'm stuck with sending emails with queues in Laravel 4. Let me describe my problem:
This works:
Mail::send('emails.validateEmail', array("username" => Input::get("username"), "code" => $code), function($message){
$message->to(Input::get('email'), Input::get('username'))
->subject('Some subject');
});
However this doesn't work:
Mail::queue('emails.validateEmail', array("username" => Input::get("username"), "code" => $code), function($message){
$message->to(Input::get('email'), Input::get('username'))
->subject('Some subject');
});
I created failed_jobs table where I keep all failed jobs from worker and in that table I found this error:
{"job":"mailer#handleQueuedMessage","data":{"view":"emails.validateEmail","data":{"username":"some_username","code":"MMgNSoaFcyGoIy10sIKgkwUOdux3tM"},"callback":"C:38:\"Illuminate\\Support\\SerializableClosure\":155:{a:2:{i:0;s:126:\"function ($message) {\n $message->to(\\Input::get('email'), \\Input::get('username'))->subject('Some subject');\n};\";i:1;a:0:{}}}"}}
Also I found this:
http://forumsarchive.laravel.io/viewtopic.php?id=12672
.. I followed all instructions from previous link but I'm keep getting this error message.
Does anyone knows how to solve this?
EDIT: emails.validateEmail file
Hello {{ $username }}!<br>
<p>some text</p><br>
{{ URL::route("validate") }}?code={{ $code }}&username={{ $username }}<br><br>
some more text
Looking at your error job - it seems like it is passing in the Input::get() commands into the serialization, rather than the data from those commands.
So I think you need to do something like this to make it work:
$data['email'] = Input::get('email');
$data['username'] = Input::get('username');
Mail::queue('emails.validateEmail', array("username" => Input::get("username"), "code" => $code), function($message) use ($data){
$message->to($data['email'], $data['username'])->subject('Some subject');
});
Related
can you help me figure out a way to use the email class of CI4 to send an email with an HTML as the message?
in Codeigniter 3 it is simple and goes like this:
$email->message($this->load->view('html_page_to_send_from_view_folder',$data,true));
but in Codeigniter 4 I tried doing this:
$email->setMessage(echo view('html_page_to_send_from_view_folder',$data,true));
It gives out an error:
syntax error, unexpected echo(T_ECHO), expecting ')'
I also tried putting the view in a variable like so:
$echo_page = echo view('html_page_to_send_from_view_folder',$data,true);
$email->setMessage($echo_page);
but it just throws the same error, I was searching all over the internet and the documentation but couldn't find a way to do this. Help please.
I tried this but got no error, and also got no email :'(
$echo_page = view('html_page_to_send_from_view_folder',$data,true);
$email->setMessage($echo_page);
According to this, if you want to use some template as your message body, you should do something like this:
// Using a custom template
$template = view("email-template", []);
$email->setMessage($template);
CodeIgniter 4 documentation states:
setMessage($body)
Parameters: $body (string) – E-mail message body
Returns: CodeIgniter\Email\Email instance (method chaining)
Return type: CodeIgniter\Email\Email
Sets the e-mail message body:
$email->setMessage('This is my message');
Okay I got it now I made it work by adding this code $email->setNewLine("\r\n"); at the end just after the setMessage:
$email->setMessage($my_message);
$email->setNewLine("\r\n");
and also I set the SMTP port 587 instead of 465:
$config['SMTPPort']= 587;
ALSO, for the setMessage, I did it like this:
$my_message = view('html_page_to_send_from_view_folder',["id" => $data['id']]);
$email->setMessage($my_message);
really weird man....
A. Firstly,
Instead of:❌
$echo_page = echo view('html_page_to_send_from_view_folder',$data,true);
Use this:✅
$echo_page = view('html_page_to_send_from_view_folder',$data);
Notice the luck of an echo statement and not passing true as the third argument of the view(...) hepler function.
B. Secondly, to submit HTML-based emails, ensure that you've set the mailType property to html. This can be achieved by using the setMailType() method on the Email instance. I.e:
$email->setMailType('html');
Alternatively, you could set the "mail type" by passing an array of preference values to the email initialize() method. I.e:
public function sendMail(): bool
{
$email = \Config\Services::email();
$email->initialize([
'SMTPHost' => 'smtp.mailtrap.io',
'SMTPPort' => 2525,
'SMTPUser' => '479d7c109ae335',
'SMTPPass' => '0u6f9d18ef3256',
'SMTPCrypto' => 'tls',
'protocol' => 'smtp',
'mailType' => 'html',
'mailPath' => '/usr/sbin/sendmail',
'SMTPAuth' => true,
'fromEmail' => 'from#example.com',
'fromName' => 'DEMO Company Name',
'subject' => 'First Email Test',
]);
$email->setTo('to#example.com');
$email->setMessage(view('blog_view'));
$response = $email->send();
$response ? log_message("error", "Email has been sent") : log_message("error", $email->printDebugger());
return $response;
}
I'm using the AWS SDK for PHP (version 3.52.33, PHP version 7.2.19) and trying to send emails using the Simple Email Service (SES). I have SES configured, and can run the example code successfully. To make my life easier, I wrote a function to send emails (send_email.php):
<?php
// Path to autoloader for AWS SDK
define('REQUIRED_FILE', "/path/to/vendor/autoload.php");
// Region:
define('REGION','us-west-2');
// Charset
define('CHARSET','UTF-8');
// Specify Sender
define('SENDER', 'sender#xxxx.com');
require REQUIRED_FILE;
use Aws\Ses\SesClient;
use Aws\Ses\Exception\SesException;
function send_email($htmlBody,$textBody,$subject,$recipient) {
$access_key = 'accessKey';
$secret_key = 'secretKey';
$ret_array = array('success' => false,
'message' => 'No Email Sent'
);
$client = SesClient::factory(array(
'version' => 'latest',
'region' => REGION,
'credentials' => array(
'key' => $access_key,
'secret' => $secret_key
)
));
try {
$result = $client->sendEmail([
'Destination' => [
'ToAddresses' => [
$recipient,
],
],
'Message' => [
'Body' => [
'Html' => [
'Charset' => CHARSET,
'Data' => $htmlBody,
],
'Text' => [
'Charset' => CHARSET,
'Data' => $textBody,
],
],
'Subject' => [
'Charset' => CHARSET,
'Data' => $subject,
],
],
'Source' => SENDER,
]);
$messageId = $result->get('MessageId');
$ret_array['success'] = true;
$ret_array['message'] = $messageId;
echo("Email sent! Message ID: $messageId" . "\n");
} catch (SesException $error) {
echo("The email was not sent. Error message: " . $error->getAwsErrorMessage() . "\n");
$ret_array['message'] = $error->getAwsErrorMessage();
}
return $ret_array;
}
This works when called from a simple testing script (test.php) in a terminal:
<?php
ini_set('display_errors','On');
error_reporting(E_ALL | E_STRICT);
require_once './send_email.php';
$email = 'test#email.com';
$htmlbody = 'test';
$txtbody = 'test';
$subject = 'test email';
$success = send_email($htmlbody,$txtbody,$subject,$email);
I get output like:
[~]$ php test.php
Email sent! Message ID: 0101016c8d665369-027be596-f8da-4410-8f09-ff8d7f87181b-000000
which is great. However, I'm doing this to send automated emails from a website (new user registration, password resets, ...) and when I try to use send_email from within a larger script I get a ~%50 success rate (when using a constant email address). Either it works and everything is fine, or it fails without an error message:
The email was not sent. Error message:
I know that an exception is being thrown, as I'm ending up in the catch statement, but I don't know how to get more information about what went wrong since there isn't a message associated with the exception. I've tried expanding what I look for in the catch block:
<snip>
catch (SesException $error) {
echo("The email was not sent. Error message: " . $error->getAwsErrorMessage() . "\n");
$ret_array['message'] = $error->getAwsErrorMessage();
$ret_array['errorCode'] = $error->getAwsErrorCode();
$ret_array['type'] = $error->getAwsErrorType();
$ret_array['response'] = $error->getResponse();
$ret_array['statusCode'] = $error->getStatusCode();
$ret_array['isConnectionError'] = $error->isConnectionError();
}
but when it fails everything is NULL except isConnectionError = false. Anecdotally, it is totally random -- I haven't been able to discern a pattern at all as to when it works and when it fails.
One other potentially relevant note: if I loop the email sending so a new user gets 10 emails, either they all succeed or they all fail.
So, does anyone have any suggestions as to what might be going wrong, or other steps I could take to help diagnose why this is happening?
For anyone running in to a similar issue in the future, I eventually came up with two solutions:
Initially, I gave up hope on the AWS SDK and switched to using PHPMailer which avoided the issue (though I believe at the cost of a loss in performance).
The real issue (I'm fairly certain now) was a mismatch in the versions of PHP between my CLI and what the webserver was providing. This question got me thinking about how that might be the issue. By updating the version of cURL and PHP that the webserver was using, I resolved the issue.
I am stuck on the point where i want to send an email using ajax. Find code below.
$user = \Auth::user();
Mail::send('emails.reminder', ['user' => $user], function ($message) use ($user) {
$message->from('xyz#gmail.com', 'From');
$message->to($request['to'], $name = null);
// $message->cc($address, $name = null);
// $message->bcc($address, $name = null);
$message->replyTo('xyz#gmail.com', 'Sender');
$message->subject($request['subject']);
// $message->priority($level);
if(isset($request['attachment'])){
$message->attach($request['attachment'], $options = []);
}
// Attach a file from a raw $data string...
$message->attachData($request['message'], $name = 'Dummy name', $options = []);
// Get the underlying SwiftMailer message instance...
$message->getSwiftMessage();
});
return \Response::json(['response' => 200]);
Now i want to send this email using ajax and upon request complete i want to display message on same page that your message sent successfully.
i found the solution for this, but this is to send plain message directly using Mail::raw() function which is working perfectly. But i am not able to attach files here or some html codes.
Any suggestion in this regard.
Im trying to send mail from laravel and when i add the dynamic from field i get this error:
"Expected response code 250 but got code "501", with message "501 A syntax error was encountered in command argument.."
this is the code:
$user = Input::get('user');
Mail::send('template.contact', $user , function($message) use ($user)
{
$email = $user['email'];
$message->from($email , 'name'); thats doesnt
//$message->from('us#example.com', 'Laravel'); that work
$message->to('test#gmail.com', 'contact us' )->subject($user['subject']);
});
and the user is coming from angular -
service:
this.sendConatctMail = function(data) {
return $http.post('send-contact-mail', {user: data});
}
and controller:
contactService.sendConatctMail($scope.user);
Here's one way you can solve this.
Let's assume the data on this.sendConatctMail = function(data) { is a object like this:
var data {
email: 'some#email.com',
// other field: values
}
Right before you post it, you should convert it into JSON string like this:
return $http.post('send-contact-mail', {user: JSON.stringify(data)});
Then on Laravel/PHP side, decode that back into an array and use it like this:
if (Input::has('user'))
{
// Decode json string
$user = #json_decode(Input::get('user'), true);
// Proceed if json decoding was success
if ($user)
{
// send email
Mail::send('template.contact', $user , function($message) use (&$user)
{
$message->from($user['email'], 'name')
->to('test#gmail.com', 'contact us')
->subject($user['subject']);
});
}
}
I don't know if this will help you, but whenever I send emails through Laravel, I need to alter the use(...) section a bit. You have:
$user = Input::get('user');
Mail::send('template.contact', $user , function($message) use ($user)
...
Try changing it to this and see what happens:
$user = Input::get('user');
Mail::send('template.contact', array('user' => $user), function($message) use (&$user) {
$message->from($user['email'], $user['name']);
$message->to('test#gmail.com', 'contact us')->subject($user['subject']);
}
2 changes I made:
array('user' => $user)
and
use(&$user)
I don't know if that will help you, but I have working emails on my application that look almost identical to yours, except for the &$variable instead of just $variable
Good luck!
The problem is with your $email = $user['email'];
try checking your $user['email']
if $message->from('us#example.com', 'Laravel'); this works
then
$email = $user['email'];
$message->from($email , 'name');
this must work...
I have tried the same without much trouble...
In my application I needed to pass the _token variable in all my ajax request any such problems??
I'm having an issue.
I try to send an activation link when the user signs up but the mail class keeps giving me this error:
{"error":{"type":"ErrorException","message":"json_encode(): Invalid UTF-8 sequence in argument","file":"C:\\BitNami\\wampstack-5.4.25-0\\apache2\\htdocs\\zplus\\vendor\\filp\\whoops\\src\\Whoops\\Handler\\JsonResponseHandler.php","line":106}}
I changed the variables $message, $subject, and even the email $email.Nothing works and I cannot solve the problem.
If I remove the mail function, then there are no problems.
Controller code
$email = Input::get('email');
Mail::queue('emails.auth.activate', array('activation_code' => $activation_code), function($message) use ($email)
{
$message->to($email, "ZL")->subject(trans("global.user_activation"));
});
Auth::loginUsingId($this->user->id);
$data = array('status' => 'success', 'redirect' => URL::to('/'));
return Response::json($data);
Could please someone help me out?
In my case problem was caused by 'driver' => 'sendmail' in app/config/mail.php. Try to use other driver or smpt.