Unable to move mails to sent folder of IMAP using Laravel - php

I am sending emails from my laravel website using SMTP. When i send email to the user then i want to copy that mail to IMAP sent folder too.
Here is my code when i am sending mail to user:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
$result = imap_append($imapStream,$path,$mail->getSentMIMEMessage());
imap_close($imapStream);
Also I tried using imap_mail_move() method like so:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
imap_mail_move($imapStream,$mail,$path);
imap_close($imapStream);
Both ways it didn't worked out
In ComplaintMail class, build function looks like :
public function build()
{
return $this->from($this->sender)
->subject($this->subject)
->markdown('emails.complaint');
}

Related

Userfrosting ExtendedMailMessage not clearing attachments

I am using the ExtendedMailMessage class to try and send an email with an attachments to my clients. The issue is I am sending the email inside a foreach loop and for some reason even though I am defining a new attachment the new attachment is just being appended to an array and each client gets multiple attachments instead of one.
$extendedMailer = $this->ci->extendedMailer;
foreach ($emails as $email) {
$attachment = new MailAttachment(
base64_decode($base64String), "report.pdf"
);
try {
$message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');
$message->from($config['address_book.admin'])
->addEmailRecipient(new EmailRecipient($email, 'Client'))
->setFromEmail($config['address_book.admin'])
->setReplyEmail($config['address_book.admin'])
->addAttachment($attachment);
$extendedMailer->sendDistinct($message);
}
catch(\Exception $ex) {
var_dump($email);
}
}
The first client will receive 1 attachment and then the 2nd will receive 2 attachments, 3rd will receive 3 attachments etc...
How do I just send 1 attachement with each email instead of appending it to the old attachments
Since PHPMailer instance is reused for each email, anything set on PHPMailer is carried on to the next email. When the Mailer's send or sendDistinct methods are called, only the recipients are explicitly cleared. So in your case, you might need to explicitly clear the attachement from $message between each email (depending how your addAttachment is implemented).
Another solution might be to move the addAttachment call outside the loop, assuming each email as the same attachement :
$extendedMailer = $this->ci->extendedMailer;
$attachment = new MailAttachment(
base64_decode($base64String), "report.pdf"
);
$message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');
$message->from($config['address_book.admin'])
->setFromEmail($config['address_book.admin'])
->setReplyEmail($config['address_book.admin'])
->addAttachment($attachment);
foreach ($emails as $email) {
try {
$message->addEmailRecipient(new EmailRecipient($email, 'Client'));
$extendedMailer->sendDistinct($message);
}
catch(\Exception $ex) {
var_dump($email);
}
}
Note that the following fix will be introduced in UserFrosting V5 send/sendDistinct to avoid this issue :
// Clone phpMailer so we don't have to reset it after sending.
$phpMailer = clone $this->phpMailer;

Swiftmailer pdf attachment from snappy bundle

I have an function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request).
This function downloads a pdf with information from objects everything works fine.
This is the function:
public function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request): Response
{
//search id
$workOrder = $this->getDoctrine()->getRepository(WorkOrders::class)->find($id);
//data to pdf template
$html = $this->renderView('pdf/pdf.html.twig', array(
'workOrder' => $workOrder,
));
//name file
$filename = $workOrder->getId();
//download pdf
return new PdfResponse(
$snappy->getOutputFromHtml($html),
$filename.'.pdf'
);
}
And then I have an swift mailer function:
//check if signed and if check is true
if ($data_uri) {
//send workOrder to company
if ($check == true) {
$transport = (new \Swift_SmtpTransport('smtp.sendgrid.net', 587))
->setUsername('sendgridUSERNAME')
->setPassword('sendgridPASSWORD')
;
$mailer = new \Swift_Mailer($transport);
$message = (new \Swift_Message('Werkbon '.$workOrder->getTitel()))
->setFrom(['xxx' => 'xxx'])
->setTo('xxx')
->setBody('xxx')
->attach(\Swift_Attachment::fromPath($this->downloadPdf()))
;
$result = $mailer->send($message);
}
The email works fine but I want to attach the pdf from the other function to this email in the code above you can see what I tried but I think I got it totally wrong.
I have no idea where to start.
Can someone give me a little push in the right direction?
Thanks!
here is how it works for me,
$invoicepdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($html);
/* And instead of returning pdf, send it with mailer: */
$message = \Swift_Message::newInstance()
->setSubject('YOUR_TITLE')
->setFrom('foo#from.net')
->setTo('foo#to.net')
->attach(\Swift_Attachment::newInstance($invoicepdf, 'your_file_name','application/pdf'))
->setBody("yyy");
$mailer->send($message);

Emulating successful send via phpmailer ($mail->Send())

When I'm building and testing my website on local server, I would like to emulate successful sending via phpmailer, so I avoid actually sending emails.
I normally use if ($mail->Send()) { the mail was sent, now do this }.
For local testing I think the best would be to skip the whole phpmailer inclusion, instead of adding a lot of if statements etc.
But skipping phpmailer would then cause php to complain about $mail->Send(), $mail->addAddress('emailaddress') etc.
How could I fake the function (or object/class) so that calls to $mail->Send() are always true, and the rest $mail->something() etc. are just ignored/true, so that no email is sent?
Extend the PHPMailer class and override the public function send().
class UnitTestMailer extends PHPMailer {
public function send() {
return $this;
}
}
class User {
public function __construct(PHPMailer $mailer) {
$this->mailer = $mailer;
}
public function sendActiviation() {
return $this->mailer->send();
}
}
// ... somewhere in your test
public function test_if_from_is_properly_set() {
// ...
$user = new User(new UnitTestMailer);
// ...
$mailer = $user->sendActivation();
$this->assertEquals($expectedFrom, $mailer->From);
}
Why emulate?
I use INI files to provide configuration variables for PHPMailer depending on the environment. Live obviously has the server's mail settings. Local uses my Gmail account credentials to send mail.
You can have the best of both worlds :)
Keep a config.ini file for example somewhere in your working directory (I tend to use root but that's preference) and make sure it's in your .gitignore or similar. Your local version would look something like:
[PHPMailer Settings]
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_SMTPSECURE = "tls"
EMAIL_SMTPAUTH = "true"
EMAIL_USERNAME = "my_email#gmail.com"
EMAIL_PASSWORD = "my_password"
then in your PHP:
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . "/config.ini", true, INI_SCANNER_TYPED);
// use settings from INI file:
$foo = $ini['PHPMailer Settings']['EMAIL_HOST'];
$bar = $ini['PHPMailer Settings']['EMAIL_PORT'];
Security Bonus
Change the syntax of your INI file to look like the below and rename it to config.ini.php:
; <?php
; die();
; /*
[PHPMailer Settings]
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_SMTPSECURE = "tls"
EMAIL_SMTPAUTH = "true"
EMAIL_USERNAME = "my_email#gmail.com"
EMAIL_PASSWORD = "my_password"
; */ ?>
(remember to use the new filename in your PHP code)
PHP can still parse the settings, but if anyone tried to access the INI file it would be parsed as PHP comments and just show ";"

Symfony, swiftmailer, incorrect email

I use swift mailer for send email, and after send email in box I have mail without html, like in screen
but in another mail services everything fine
this my code
public function createMessage($subject, $receivers, $template, $context)
{
$message = \Swift_Message::newInstance($subject);
$message->setFrom($this->from_address);
$message->setTo($receivers);
$body = $this->twig->render($template, $context);
$plaintext = strip_tags($body);
$message->setBody($body, "text/html");
$message->addPart($plaintext, "text/plain");
$this->mailer->send($message);
}
What problem in this code? I set body test/html. What problem not understand
Try with this:
public function __construct(Container $oContainer) {
$this->oContainer = $oContainer;
}
$this->oContainer->get('templating')->render()
And set the content yourself:
$message->setContentType('text/html');

How to send mail using cake php and where to start?

I wanna try to send mail using cake php. I have no experience of sending mail. So, I don't know where to start. Is it need to make mail server? If need, how to make mail server and how to send mail? Please explain step by step. I really don't know where to start.
I'm using xampp and now I test my site at localhost.
I tested following link:
http://book.cakephp.org/view/1286/Sending-a-basic-message
but error occurred cannot be accessed directly.
and then I add code from the following link:
http://book.cakephp.org/view/1290/Sending-A-Message-Using-SMTP
So, my code is following:
function _sendMail(){
$this->Email->to = 'user#gmail.com';
$this->Email->bcc = array('secret#example.coom');
$this->Email->subject = 'Welcome to our really cool things';
$this->Email->replyTo = 'support#example.com';
$this->Email->from = 'Online Application <app#example.coom>';
$this->Email->template = 'simple_message';
$this->Email->sendAs = 'both';
$this->Email->smtpOptions = array(
'port' =>'25',
'timeout' => '30',
'host' => 'ssl://smtp.gmail.com',
'username' => 'my_mail#gmail.com',
'password' =>'aaa',
);
$this->Email->delivery = 'smtp';
$this->Email->send();
}
but error still occurred. But, I didn't make any mail server.Is that OK?
I have a feeling this is to do with your XAMPP configuration:
Try opening "php.ini", it should be somewhere in your server files.
Search for the attribute called “SMTP” in the php.ini file.Generally you can find the line “SMTP=localhost“. change the localhost to the smtp server name of your ISP. And, there is another attribute called “smtp_port” which should be set to 25.I’ve set the following values in my php.ini file.
SMTP = smtp.wlink.com.np
smtp_port = 25
Restart the apache server so that PHP modules and attributes will be reloaded.
ow try to send the mail using the mail() function:
mail(“you#yourdomain.com”,”test subject”,”test body”);
If you get the following warning:
Warning: mail() [function.mail]: “sendmail_from” not set in php.ini or custom “From:” header missing in C:\Program Files\xampp\htdocs\testmail.php on line 1
Specify the following headers and try to send the mail again:
$headers = ‘MIME-Version: 1.0′ . “\r\n”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1′ . “\r\n”;
$headers .= ‘From: sender#sender.com’ . “\r\n”;
mail(“you#yourdomain.com”,”test subject”,”test body”,$headers);
source: http://roshanbh.com.np/2007/12/sending-e-mail-from-localhost-in-php-in-windows-environment.html
Naming the controller function with a leading underscore is Cake's backwards compatible way of designating that the function should be protected, i.e. that the function should not be accessible as a normal controller action. That means you can't access FooController::_sendMail() using the URL /foo/_sendMail, or any other URL for that matter. You should be seeing this, which IMO is a pretty good error message:
Private Method in UsersController
Error: FooController::_sendMail() cannot be accessed directly.
Remove the leading underscore, that's all. This problem has nothing to do with sending email.
Try:
//load mail component in controller
var $components = array('Mail');
//then do
$this->Email->sendAs="html";
$this->Email->from="some#domain.com";
$this->Email->to="someone#domain.com";
$this->Email->subject="Your subject;
$this->Email->send("Your message);
//Check cakephp manual for more reference: http://book.cakephp.org/
Here is an example code for sending an HTML email with CakePHP's Email component
Ex controller : EmailController.php
<?php
class EmailController extends AppController{
public $components=array('Email');
function send(){
//create an array of values to be replaced in email html template//
$emailValues=array('name'=>'MyName','phone'=>'MyPhone');
$this->set('emailValues',$emailValues);//pass to template //
$this->Email->to = 'to#address.com'; //receiver email id
$this->Email->subject = 'Subject Line';
$this->Email->replyTo = 'reply#address.com'; //reply to email//
$this->Email->from = 'SenderName<sender#address.com>'; //sender
$this->Email->template = 'sample';//email template //
$this->Email->sendAs = 'html';
if($this->Email->send()){
//mail send //
}
}
?>
Now create the email template in folder /Views/Email/html/
ie the template path should be
/Views/Email/html/sample.ctp
sample.ctp
<?php
Hi <?php echo $emailValues['name'];?> <br>
Thanks for sharing your phone number '<?php echo $emailValues['phone'];?>' .
<br>
?>

Categories