i want to use config that i get from html form and i dont want to get it from config/mail.php or .env file
how can i do that in laravel 8
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($address = 'contact#example.com', $name = $this->data['from'])
->subject($this->data['subject'])
->view('mail.view')
->smtp('mail.example.com')
->port('587')
->username('username')
->password('pass')
->smtp('mail.example.com')
->with(['message' => $this->data['message']]);
}
you can use swiftmailer to send any type of mail you want (laravel use this under the hood):
$transport = (new Swift_SmtpTransport("smtp.gmail.com", "587", "tls"))
->setUsername('username')
->setPassword('pass');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message("subject")) // email subject
->setFrom(['contact#example.com' => "sender name"]) // sender mail and display name
->setTo("receiver#gmail.com") // replace with your receiver mail variable
->setBody("<h2>Test</h2>", 'text/html');
$result = $mailer->send($message); // send the mail
if you want to send from queue instead of in controller directly, you can create queue and pass mail parameter to queue construct
Related
I am building this website and on one of the pages I have a contact form from which the user should be able to send a message to us.
.env :
###> symfony/google-mailer ###
# Gmail SHOULD NOT be used on production, use it in development only.
MAILER_DSN=gmail://myEmail.com:myPassword#default?verify_peer=0
###< symfony/google-mailer ###
mailer.yaml :
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
the code that is supposed to send the mail :
/**
* #Route("/contact", name="api_mail")
*/
public function mailAPI(Request $request, MailerInterface $mailer)
{
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = $_POST["Name"];
$mail = $_POST["Mail"];
$game = $_POST["Game"];
$category = $_POST["Categ"];
$message = $_POST["Msg"];
$email = (new Email())
->from($mail)
->to('myEmail#gmail.com')
->subject('Testing the mail sender from symfony.')
->text($message)
->html('<p> This is a message </p>');
$mailer->send($email);
}
return $this->render('default/index.html.twig', [
'controller_name' => 'DefaultController',
]);
}
}
At first I used mailCatcher and it caught the mails, now I configured the gmail thingy to send the mails via the gmail transport but it doesn't do anything.
I'm trying to send an email when a user is subscribing in my web site.
To save me time ... I'm using Swift_Mailer with Symfony.
First, I tried to send a mail with the console :
php .\bin\console swiftmailer:email:send
And that's working, the mail was sent and the client received it.
So now I said to myself, I will be able to send emails with the code.
That's my Controller code :
public function register(Request $request, \Swift_Mailer $mailer)
{
// Here saving new user in the database
$this->sendMail($user->getEMail(), $mailer);
$content = $this->renderView("register.html.twig");
return new Response($content);
}
private function sendMail($email, \Swift_Mailer $mailer)
{
$message = (new \Swift_Message('Hello Email'))
->setFrom(['my.email#gmail.com' => "my name"])
->setTo($email)
->setBody('Here is the message itself');
$mailer->send($message);
}
And That's my .env file :
MAILER_URL=gmail://my.email#gmail.com:myPasswordHere#localhost
When I'm trying to send the mail, no error, I tried this StackOverflow link, but no problem, echo "Successfull", but nothing in the Gmail send box and nothing my client email box.
Can you please help me to ... save me time ^^
------------------------------------------------------------- EDIT 1 ------------------------------------------------------------
I never edited the config/packages/swiftmailer.yaml file, that's it's content :
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
------------------------------------------------------------- EDIT 2 ------------------------------------------------------------
I also tryed to make a new transporter with this code :
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465))
->setUsername('my.email#gmail.com')
->setPassword('myPasswordHere');
$mailer = new \Swift_Mailer($transport);
And that's the error I get : Connection could not be established with host smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: Unknown host. #0]
------------------------------------------------------------- EDIT 3 ------------------------------------------------------------
I've got a swiftmailer.yaml fil in the config/packages/dev folder and that's it's default content :
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me#example.com']
I tried to put the same content as in the config/packages/swiftmailer.yaml, but no result.
I don't see something like this in your code:
// Create the Transport
$transport = (new \Swift_SmtpTransport('mail hoster etc', port))
->setUsername('your email')
->setPassword('your password');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
Maybe it's a reason why your mails isn't sent.
I'm using Yii framework while my question is probably intended to PHP expert.
I have created a controller to send email from my web application, it works fine.
Given that, I intend to use email in several sontrollers in my app, I wanted to created a helper but that does not work. Email is not sent. (I'm using swiftmailer)
The code of the working controller is the following:
<?php
class MailController extends Controller
{
/**
* Declares class-based actions.
*/
public function actionSendemail() {
// Plain text content
$plainTextContent = "This is my first line ;-)\nThis is my second row of text";
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport mailHost= localhost, mailPort = 25
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage('My subject')
->setFrom(array('test1#localhost.localdomain' => 'Example Name'))
->setTo(array('myemail#domain.com' => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($plainTextContent);
// Send mail
$result = $Mailer->send($Message);
}
}
The helper code is the following
<?php
// protected/components/Email.php
class Email {
public static function sendEmail($subject, $from, $to, $body)
{
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage($subject)
->setFrom(array($from => 'Example Name'))
->setTo(array($to => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($body);
// Send mail
$result = $Mailer->send($Message);
}
}
the way I call it is the following
$subject= 'My subject';
$from = Yii::app()->params['adminEmail']; // adminEmai is a globalparam like above controller
$to='xxxx#xxx.com';
$body='my body';
Email::sendEmail($subject, $from, $to, $body);
when I run this code, I have no error, but I dont receive the email.
Thank you for your help.
I found my error.
my global parameters in config.php was not set correctly.
So content I put in the from field was not recognized by my hmailserver which is configured for the moment with the content test1#localhost.localdomain
sorry for the question and thanks
I have a config array with some smtp settings.
I am looking for a way to extend Swiftmailer to auto fill in these details.
I cannot find anything about extending swiftmailer. I did found some information about plugins, but these existing plugins of swiftmailer won't tell me anything.
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody('Body')
;
$result = $mailer->send($message);
Can anyone tell me how to do this?
I don't see why you should extend SwiftMailer for that requirement. It's much easier to create a class that handles the preparation e.g.
class SwiftMailerPreparator {
private $mailer;
public __construct(Swift_Mailer $mailer) {
$this->mailer = $mailer;
}
public function prepare(array $settings) {
// do your thing here
}
}
Also since SwiftMailer is opensource you can just look at the code and see how it works.
You could wrap everything into a service class like this:
class MyMailerAssistant
{
/**
* Service method to fastly send a message
* #param $subject
* #param $body
*/
public static function sendMessage($subject, $body)
{
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setSubject($subject)
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody($body);
$result = $mailer->send($message);
}
}
and calling it simply in this way:
MyMailerAssistant::sendMessage('Hello', 'This is the email content');
Anyway I strongly discourage you inserting your configuration into a method, I would always load it from a modular external configuration file.
With php mail http://php.net/manual/en/function.mail.php if the mail is sent ok it returns true.
But with my web host the sent rate is 3000/hour and the server will then store 450 e-mails after the 3000 limit has been reached (which is 15% of the 3000 limit).
What I would like confirmation of is that when the php mail function returns true is it coping with these settings. Does the mail server confirm to the mail function that it sent OK or is the mail function 'blind' to that?
Does the mail server say to the function, limit reached email not sent so return false?
Using the mail() function that comes with PHP is not an optimal solution. Use SWIFTMAILER http://swiftmailer.org/ This will use as SMTP service:
Example of code when using swiftmailer as SMTP service:
require_once 'lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
->setUsername('your username')
->setPassword('your password')
;
/*
You could alternatively use a different transport such as Sendmail or Mail:
// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Mail
$transport = Swift_MailTransport::newInstance();
*/
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);