How to send email with dynamic sender in laravel? - email

I am creating a simple contact us from in Laravel.
I set up .env with my Gmail account. I can send email from Laravel with my email address, no problem with this.
But, I want to send email from sender address who is sending the message form contact us form.
Here is my code in controller:
public function sendMessage(Request $request)
{
$this->validate($request,[
'email'=>'required|email',
'subject'=>'required',
'body'=>'required|max:150'
]);
$body = $request['body'];
Mail::send('emails.support',['body' => $body], function($message){
$email = Input::get('email');
$subject = Input::get('subject');
$message->sender($email);
$message->to('smartrahat#gmail.com','Mohammed');
$message->subject($subject);
});
return redirect('contactUs');
}
Though, I am getting email address form contact us form, the email always sent form my email account which I configured in .env

I would have done some things different. I guess $body is the email-text? You should put this in a array and add it as a parameter in Mail::send (or directly put $request->all() as a parameter.
Also, inside of the closure of Mail, i don`t thinks its very nice to put logic there (like $email=Input::get). It does not look right if you ask me.
Didn`t test this code, but this should work:
public function sendMessage(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'subject' => 'required',
'body' => 'required|max:150'
]);
$data = [
'email' => $request->input('email'),
'subject' => $request->input('subject'),
'body' => $request->input('body')
];
Mail::send('emails.support', $data, function($message) use ($data)
{
$message->from($data['email']);
$message->to('smartrahat#gmail.com','Mohammed');
$message->subject($data['subject']);
});
return redirect('contactUs');
}
Because you add $data as as 'use', you can access this data inside the closure. The $data send as a parameter, can be used in the email blade. In this example, you can access the data like this: $email , $subject , $data, in blade these will output the values.
But you can also do it like this:
Mail::send('emails.support', $request->all(), function($message) use ($data)

public function reset_password(Request $request)
{
$user=User::whereEmail($request->email)->first();
if(count($user) == 1)
{
$data = array('name'=>"Virat Gandhi");
$subject=$request->email;
mail::send(['emails'=>'reset_set'],$data,
function($message)use($subject)
{
$message->from('your#gmail.com','kumar');
$message->to($subject);
$message->subject($subject);
});
echo "Basic Email Sent. Check your inbox.";
}
}

foreach ($emails as $value1)
{
$to[]=implode(',',$value1['0']);
}
$subject=$request->input('sub');
$mailsend=Mail::send('email.subscribe',$mail_content,
function($message)use($to,$subject)
{
$message->from('ganarone#ganar.io','Ganar');
$message->to($to);
$message->subject($subject);
});

Related

Laravel-why admin receives every email message?

I am working on a web application with multiple users, and I have some issue with sending emails.
Sending is working fine, no problems, but the issue is that every mail interaction between visitors and users is sent to admin email address stated in env file. I am using gmail for sending, Laravel 8.
For example, visitor A has sent a message to user B. User B received mail correctly, but also admin received message.
Thanks for help.
Here is my EmailsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
class EmailsController extends Controller
{
public function send(Request $request)
{
function sentence_case($string) {
$sentences = explode(" ",$string);
$sentences = array_reverse($sentences);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string = ucfirst(mb_strtolower(trim($sentence)))." ".$new_string;
}
return $new_string;
}
$this->validate($request, [
'ime' => 'required', //visitor name
'email' => 'required', // visitor email address
'poruka' => 'required' //visitor message
]);
$ime = $request->get('ime');
$ime = sentence_case($ime);
$email = $request->get('email');
$poruka = $request->get('poruka');
Mail::send('emails.message', [
'name' => $ime,
'email' => $email,
'comment' => $poruka ],
function ($m) use ($email) {
$m->from($email);
$m->to('usersemail#yahoo.com', 'MyApp')
->subject('Website Contact Form');
});
/* usersemail#yahoo.com is registered user email address different from aplication admin/owner email addres stated in env file, but admin receives this message */
if (Mail::failures()) {
return response()->Fail('Sorry! Please try again latter');
}else{
return back()->with('success', 'Thanks for contacting me, I will get back to you soon!');
}
}
}

Store email body in table using Laravel 5.3 Mailable

I want to store the email body in my communications table. My controller:
Mail::to($user->email)->send(new WelcomeEmail($subscription));
Communication::create([
'to' => $user->email,
'subject' => 'Welcome Email',
'body' => '???'
]);
My email goes out (successfully) and I am able to create a Communication record, but have no idea how to retrieve the email body.
After reading the Mail manual, I thought I could work with an event:
protected $listen = [
'Illuminate\Mail\Events\MessageSending' => [
'App\Listeners\LogSentMessage',
],
];
But here I get only the full plain text email. If I create an instance of the mail, with:
$email = Mail::to($user->email)->send(new WelcomeEmail($subscription));
the outcome of dd($email); is null.
Some extra info, in my WelcomeEmail.php, I am using a view:
public function build()
{
return $this->view('emails.welcome_email');
}
You can directly do this to render Mailable and store it in a variable
$html = (new WelcomeEmail($subscription))->render();
I found a solution, hopefully it can help other people.
$body = View::make('emails.welcome_email')
->with('subscription', $this->subscription)
->with('template', $this->template)
->render();
I rendered the view and saved it in the body variable.

Laravel4: check if the inserted email is in a proper format

In my app there is a little form with subscription to newsletter.
The form has just one field: email.
I want that when the entry is not in a proper email format, instead of throwing a laravel error: Address in mailbox given [fghfghfhf] does not comply with RFC 2822, 3.6.2.
I want to, more elegantly, give a validation error.
How can i define this rule?
Thanks!
EDIT:
This is my NewsletterUser model:
class NewsletterUser extends Eloquent {
protected $table = 'newsletterusers';
protected $guarded = array();
public static $rules = array(
'email' => 'required | email | unique:newsletterusers'
);
public static $messages = array(
'email' => 'You already subscribed',
'empty' => 'Insert the mail, please'
);
}
And this is the subscription method in the Controller:
public function subscription()
{
$input = Input::all();
$validation = Validator::make($input, NewsletterUser::$rules, NewsletterUser::$messages);
if($validation->passes())
{
// subscription stuff
}
return Redirect::back()->withInput()->withErrors($validation)->with('message','Insert the mail, please');
}
Just define a custom error message:
$messages = array(
'email' => 'Address in mailbox given :attribute does not comply with RFC 2822, 3.6.2.',
);
$validator = Validator::make($input, $rules, $messages);

cakephp2 how to send email using gmail smtp dynamically to a closed mailing list

Is there anyway in php or cakephp, to send email using smtp so that I can send email to a closed/internal mailing list. e.g:
In my company we have an email list: appsteam#company.com, which can only be send if a person also using xxx#company.com email. outside from that email it will be blocked. so in cakephp is there anyway to somehow take the user credential and send email under a company or maybe in gmail email, if it's google group
I think what I actually want will be, how to set up cakephp email so that it send just like I send directly from the email server, if I use gmail, then I want it looks like gmail (header, etc)
what the final code will do is supposedly, I will take credential from users for their email, and send the mail using that. here is my code for AbcComponent.php
/*
* Abc components
*/
class AbcComponent extends Component {
public $options = array();
/**
* Constructor
**/
public function __construct(ComponentCollection $collection, $options = array()){
parent::__construct($collection,$options);
$this->options = array_merge($this->options, $options);
}
public function send_link ($user_email = null, $recipients = null, $subject = null, $message = null, $group_id = null, $user_id = null, $email_id = null, $download_password = null) {
$final_subject = $subject;
$final_recipients = $recipients;
$final_message = $message;
App::uses('CakeEmail', 'Network/Email');
$recipients = str_replace(' ', '', $recipients);
$recipients = explode(',', $recipients);
$recipient_queue_num = 1;
//Send the email one by one
foreach ($recipients as $recipient) :
$email = new CakeEmail();
$email->delivery = 'smtp';
//$email->from($user_email);
$email->from('xxxxx#gmail.com');
$email->to($recipient);
$email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'xxxxx#gmail.com', //this will be later grab from dbase based on user
'password'=>'password',
);
$email->subject($final_subject);
$email->template('download_link_email');
$email->emailFormat('both');
$email->viewVars(array('final_message' => $final_message));
if($email->send()) {
debug('email is sent');
} else {
debug('email is not sent');
}
//queue number increase for hashing purpose
$recipient_queue_num++;
endforeach;
}
$this->Email->delivery = ...
and later
$email = new CakeEmail();
Where is your "new object" statement before trying to access it?
You cannot just use it without.
You are also using both $this->Email and $email. This is probably your mistake (copy and paste errors).
$this->Email = new CakeEmail();
$this->Email->delivery = ...
...
"Indirect modification of overloaded property" is usually always an indicator of a non declared object that you are trying to access.

email sending from localhost in cakephp using emailcomponent

<?php
class EmailsController extends AppController
{
var $uses=null;
var $components=array(
'Email'=>array(
'delivery'=>'smtp',
'smtpOptions'=>array(
'host'=>'ssl://smtp.google.com',
'username'=>'username#gmail.com',
'password'=>'password',
'port'=>465
)
));
function sendEmail() {
$this->Email->to = 'Neil <neil6502#gmail.com>';
$this->Email->subject = 'Cake test simple email';
$this->Email->replyTo = 'neil6502#gmail.com';
$this->Email->from = 'Cake Test Account <neil6502#gmail.com>';
//Set the body of the mail as we send it.
//Note: the text can be an array, each element will appear as a
//seperate line in the message body.
if ( $this->Email->send('Here is the body of the email') ) {
$this->Session->setFlash('Simple email sent');
} else {
$this->Session->setFlash('Simple email not sent');
}
$this->redirect('/');
}
}
?>
above code is my controller responsible for sending emails...
but when i run this function sendEmail() using url http://localhost/authentication/emails/sendemail it shows nothing not even single error or any response... complete blank page. I don't know the reason.
I think I had the same issue a while ago. It might be that you need to change the to address into a value that holds just the address, so instead of Name <email#example.com> you should use email#example.com.
You can check for errors by logging (or debugging) the smtp errors with:
$this->log($this->Email->smtpError, 'debug');
or
debug($this->Email->smtpError);
Good luck. Hope this helps.
/* Auf SMTP-Fehler prüfen */
$this->set('smtp_errors', $this->Email->smtpError);
I would add the Email Config to your email.php file located in /app/Config/email.php , if it doesn't exist copy email.php.default to email.php, Change the smtp settings there
public $smtp = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'my#gmail.com',
'password' => 'secret'
);
At the top of your Controller above class EmailsController extends AppController add,
App::uses('CakeEmail', 'Network/Email');
Then in your function sendEmail() try,
$Email = new CakeEmail();
$Email->from(array('me#example.com' => 'My Site'))
->to('you#example.com')
->subject('About')
->send('My message');
To test emails what I usually do is send them to the Cake Logs,
**In /app/Config/email.php, include: ( The log output should be /app/tmp/logs/debug.log )
public $test = array(
'log' => true
);
Also doing this add 'test' to your $Email variable like,**
$Email = new CakeEmail('test');
Actually in my case : I got a error message "SMTP server did not accept the password."
After that i follow the below link and issue has been resolved :
Step1 : https://blog.shaharia.com/send-email-from-localhost-in-cakephp-using-cakeemail/
Step2 : Sending Activation Email , SMTP server did not accept the password