本文整理汇总了PHP中Swift_Attachment::newInstance方法的典型用法代码示例。如果您正苦于以下问题:PHP Swift_Attachment::newInstance方法的具体用法?PHP Swift_Attachment::newInstance怎么用?PHP Swift_Attachment::newInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Swift_Attachment
的用法示例。
在下文中一共展示了Swift_Attachment::newInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testSend
public function testSend()
{
$message = new Swift_Message();
$message->setFrom('johnny5@example.com', 'Johnny #5');
$message->setSubject('Is alive!');
$message->addTo('you@example.com', 'A. Friend');
$message->addTo('you+two@example.com');
$message->addCc('another+1@example.com');
$message->addCc('another+2@example.com', 'Extra 2');
$message->addBcc('another+3@example.com');
$message->addBcc('another+4@example.com', 'Extra 4');
$message->addPart('<q>Help me Rhonda</q>', 'text/html');
$message->addPart('Doo-wah-ditty.', 'text/plain');
$attachment = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
$attachment2 = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
$attachment2->setDisposition('inline');
$message->attach($attachment);
$message->attach($attachment2);
$message->setPriority(1);
$headers = $message->getHeaders();
$headers->addTextHeader('X-PM-Tag', 'movie-quotes');
$messageId = $headers->get('Message-ID')->getId();
$transport = new PostmarkTransportStub('TESTING_SERVER');
$client = $this->getMock('GuzzleHttp\\Client', array('request'));
$transport->setHttpClient($client);
$o = PHP_OS;
$v = phpversion();
$client->expects($this->once())->method('request')->with($this->equalTo('POST'), $this->equalTo('https://api.postmarkapp.com/email'), $this->equalTo(['headers' => ['X-Postmark-Server-Token' => 'TESTING_SERVER', 'User-Agent' => "swiftmailer-postmark (PHP Version: {$v}, OS: {$o})", 'Content-Type' => 'application/json'], 'json' => ['From' => '"Johnny #5" <johnny5@example.com>', 'To' => '"A. Friend" <you@example.com>,you+two@example.com', 'Cc' => 'another+1@example.com,"Extra 2" <another+2@example.com>', 'Bcc' => 'another+3@example.com,"Extra 4" <another+4@example.com>', 'Subject' => 'Is alive!', 'Tag' => 'movie-quotes', 'TextBody' => 'Doo-wah-ditty.', 'HtmlBody' => '<q>Help me Rhonda</q>', 'Headers' => [['Name' => 'Message-ID', 'Value' => '<' . $messageId . '>'], ['Name' => 'X-PM-KeepID', 'Value' => 'true'], ['Name' => 'X-Priority', 'Value' => '1 (Highest)']], 'Attachments' => [['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt'], ['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt', 'ContentID' => 'cid:' . $attachment2->getId()]]]]));
$transport->send($message);
}
示例2: postUpdate
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->mailer = $this->container->get('mailer');
$this->mailerHelper = $this->container->get('stfalcon_event.mailer_helper');
$this->pdfGeneratorHelper = $this->container->get('stfalcon_event.pdf_generator.helper');
if ($entity instanceof Payment) {
if ($entity->getStatus() === Payment::STATUS_PAID) {
$tickets = $this->container->get('doctrine')->getManager()->getRepository('StfalconEventBundle:Ticket')->getAllTicketsByPayment($entity);
/** @var Ticket $ticket */
foreach ($tickets as $ticket) {
/** @var $user User */
$user = $ticket->getUser();
/** @var Event $event */
$event = $ticket->getEvent();
$successPaymentTemplateContent = $this->mailerHelper->renderTwigTemplate('StfalconEventBundle:Interkassa:_mail.html.twig', ['user' => $user, 'event' => $event]);
$mail = new Mail();
$mail->addEvent($event);
$mail->setText($successPaymentTemplateContent);
$html = $this->pdfGeneratorHelper->generateHTML($ticket);
$message = $this->mailerHelper->formatMessage($user, $mail);
$message->setSubject($event->getName())->attach(\Swift_Attachment::newInstance($this->pdfGeneratorHelper->generatePdfFile($ticket, $html), $ticket->generatePdfFilename()));
$this->mailer->send($message);
}
}
}
}
示例3: send
/**
* Méthode d'envoie d'email
*
* @param array $data
* @param array|array<UserInterface> $aEmailTo
* @param array $aAttachement
*/
protected function send($data, $aEmailTo, $aAttachement = array(), MailParametersInterface $mailParameters)
{
$mailerForSend = $this->mailer;
foreach ($aEmailTo as $user) {
//Create the message
/* @var $message \Swift_Message */
$message = \Swift_Message::newInstance()->setSubject($data['objet'])->setFrom(array($this->config['from_email']['address'] => $this->config['from_email']['sender_name']));
foreach ($aAttachement as $oneAttachment) {
$attachment = \Swift_Attachment::newInstance($oneAttachment['content'], $oneAttachment['name'], $oneAttachment['type']);
$message->attach($attachment);
}
$failedRecipients = array();
$numSent = 0;
if (is_object($user) && method_exists($user, 'getEmail')) {
$message->setTo($user->getEmail());
} elseif (is_string($user)) {
$message->setTo($user);
} else {
throw new \RuntimeException('Invalid email');
}
$message->setBody($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.html.twig', $data), "text/html");
$message->addPart($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.txt.twig', $this->getRaw($data)), "text/plain");
$numSent += $mailerForSend->send($message, $failedRecipients);
if ($this->logger && $this->config['active_log'] === true) {
$this->logger->info(sprintf("Email: '%s' sended to: '%s'", $data['objet'], current(array_keys($message->getTo()))), array('CnertaMailingBundle', 'email-sended'));
}
}
return $numSent;
}
示例4: createParticipation
public function createParticipation($user, $drink)
{
$dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
$dEndDrink = clone $dDrink;
$dEndDrink->modify('+3 hours');
$dateFormat = 'Ymd\\THis';
$icsInvite = \Swift_Attachment::newInstance()->setContentType('text/calendar;charset=UTF-8;method=REQUEST')->setBody($this->twig->render('drink/invite_ics.twig', array('user' => $user, 'drink' => $drink, 'datetimes' => array('start' => $dDrink->format($dateFormat), 'end' => $dEndDrink->format($dateFormat), 'current' => date($dateFormat)))))->setEncoder(\Swift_Encoding::getQpEncoding());
return $this->mailer->createMessage()->setSubject('[Aperophp.net] Inscription à un ' . $drink['kind'])->setFrom(array('noreply@aperophp.net'))->setTo(array($user['email']))->setBody($this->twig->render('drink/participation_mail.html.twig', array('user' => $user, 'drink' => $drink)), 'text/html')->attach($icsInvite);
}
示例5: send
public function send($to, $subject, $body, $from = null, $cc = null, $attachmentData = [])
{
$message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($from ?: $this->from)->setTo($to)->setBody($body)->setContentType('text/html');
if (isset($attachmentData['filename']) && isset($attachmentData['contentType']) && isset($attachmentData['data'])) {
$attachment = \Swift_Attachment::newInstance($attachmentData['data'], $attachmentData['filename'], $attachmentData['contentType']);
$message->attach($attachment);
}
// set carbon copy
if ($cc) {
$message->setCc($cc);
}
$this->mailer->send($message);
}
示例6: emailCsvFile
/**
* Email the CSV to the given recipients.
*
* @param $recipients
*
* @return array|string array of recipients or ; delimited list
*/
public function emailCsvFile($recipients)
{
if (!is_array($recipients)) {
$recipients = explode(';', $recipients);
}
$csv = $this->pendingApplicationsCSV();
$message = Yii::app()->mailer->newMessage();
$message->setFrom(array('noreply@openeyes.org.uk' => 'OpenEyes Reports'));
$message->setTo($recipients);
$message->setSubject('Pending Therapy Applications Report');
$message->setBody('Your report on currently pending Therapy Applications');
$message->attach(Swift_Attachment::newInstance($csv, 'PendingApplications.csv', 'text/csv'));
return Yii::app()->mailer->sendMessage($message);
}
示例7: indexAction
/**
* @Template("TestBundle:Event:index.html.twig")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EntityBundle:Orders')->findOrdersAll();
$html = $this->renderView('TestBundle:Event:index.html.twig');
$pdfgenerator = $this->get('knp_snappy.pdf');
$file = $pdfgenerator->getOutputFromHtml($html);
$attachment = \Swift_Attachment::newInstance($file, 'my-file.pdf', 'application/pdf');
$customer = new Customer();
$customer->setName('Radumta Sitepu');
$customer->setEmail('perjon_zet@ymail.com');
$message = \Swift_Message::newInstance()->setSubject('Hello Email')->setFrom('raizetacorp@gmail.com')->setTo('perjon_zet@ymail.com')->setBody($this->renderView('TestBundle:Event:index.html.twig'))->attach($attachment);
$this->get('mailer')->send($message);
return array();
}
示例8: sendMail
public function sendMail(OrderInterface $order)
{
$body = $this->render($this->template, ['order' => $order, 'translationDomain' => $this->translationDomain]);
$attach = \Swift_Attachment::newInstance();
$attach->setFilename('bill.pdf');
$attach->setContentType('application/pdf');
$attach->setBody($this->getBillingGenerator()->generate($order));
$message = $this->createMessage();
$message->addFrom($this->from);
$message->setSubject($this->getTranslator()->trans($this->subject, [], $this->translationDomain));
$message->addTo($order->getCustomerEmail());
$message->setBody($body, 'text/html');
$message->attach($attach);
$this->send($message);
}
示例9: send
public static function send($template_name, $vars)
{
$transport = Config::get('mailer.transport');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setFrom(array('sowcomposer@gmail.com' => 'SOW Composer'));
if ($template_name == "SOW_COMPLETED") {
$sow = Sow::find($vars["sow_id"]);
$attachment = Swift_Attachment::newInstance()->setFilename($sow->title . '.doc')->setContentType('application/msword')->setBody(View::make('partials.doc')->with('sow', $sow));
$message->setSubject("Here's your completed SOW, \"{$sow->title}\"")->setTo(array($sow->author_email))->addPart(View::make('mailer.sow_completed_text')->with('sow', $sow), 'text/plain')->setBody(View::make('mailer.sow_completed_html')->with('sow', $sow), 'text/html')->attach($attachment);
} else {
throw new Exception("Couldn't find the SowMailer template that you requested.");
}
$mailer->send($message);
}
示例10: sendEmail
public function sendEmail($from, $to, $cc, $subject, $body, $attachmentFilename)
{
$this->assertNotNull($this->mailer, 'Set provider first via haveMailProvider');
$message = \Swift_Message::newInstance($subject, $body, 'text/plain');
$message->addFrom($from);
$message->addTo($to);
$message->addPart("<p>{$body}</p>", 'text/html');
$message->attach(\Swift_Attachment::newInstance($body, $attachmentFilename, 'application/octet-stream'));
if (is_array($cc)) {
$message->setCc($cc);
} else {
$message->addCc($cc);
}
$this->mailer->send($message);
$this->debugSection('SmtpMailer', $subject . ' ' . $from . ' -> ' . $to);
}
示例11: testHTMLPartAppearsLastEvenWhenAttachmentsAdded
public function testHTMLPartAppearsLastEvenWhenAttachmentsAdded()
{
$message = Swift_Message::newInstance();
$message->setCharset('utf-8');
$message->setSubject('test subject');
$message->addPart('plain part', 'text/plain');
$attachment = Swift_Attachment::newInstance('<data>', 'images.gif', 'images/gif');
$message->attach($attachment);
$message->setBody('HTML part', 'text/html');
$message->setTo(array('user@domain.tld' => 'User'));
$message->setFrom(array('other@domain.tld' => 'Other'));
$message->setSender(array('other@domain.tld' => 'Other'));
$id = $message->getId();
$date = preg_quote(date('r', $message->getDate()), '~');
$boundary = $message->getBoundary();
$this->assertRegExp('~^' . 'Sender: Other <other@domain.tld>' . "\r\n" . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: Other <other@domain.tld>' . "\r\n" . 'To: User <user@domain.tld>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: multipart/mixed;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/alternative;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/plain; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'plain part' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'HTML part' . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: images/gif; name=images.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: attachment; filename=images.gif' . "\r\n" . "\r\n" . preg_quote(base64_encode('<data>'), '~') . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString());
}
示例12: dumpInfoAfterFailedStep
/**
* Send an email to the team after step failed with error message, screen, and generated html.
*
* @AfterStep
*/
public function dumpInfoAfterFailedStep(AfterStepScope $scope)
{
if ($scope->getTestResult()->getResultCode() === StepResult::FAILED && null !== $this->getScenario($scope)) {
$error = nl2br($scope->getStep()->getText()) . '<br /><br /><b style="color: red">Failed with message : ' . $scope->getTestResult()->getException()->getMessage() . '</b><br />';
$message = \Swift_Message::newInstance()->setFrom('travis@ci-tron.org')->setTo('travis@ci-tron.org')->setSubject('Error on scenario: ' . $this->getScenario($scope)->getTitle());
if ($this->minkContext->getSession()->getDriver() instanceof \Behat\Mink\Driver\Selenium2Driver) {
$screenshot = $this->minkContext->getSession()->getDriver()->getScreenshot();
$message->attach(\Swift_Attachment::newInstance($screenshot, 'screenshot.png', 'image/png'));
}
$error .= '<br /><br />Driver: "' . get_class($this->minkContext->getSession()->getDriver()) . '"';
$message->attach(\Swift_Attachment::newInstance($this->minkContext->getSession()->getPage()->getHtml(), 'page.html', 'text/html'));
$message->setBody('<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>' . $error . '</body></html>', 'text/html');
$transport = \Swift_SmtpTransport::newInstance('smtp.mailgun.org', 587)->setUsername('test@sandbox90ea023f482a4f3faf810cca3a5febb8.mailgun.org')->setPassword($this->getSmtpPassword());
$mailer = \Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
}
示例13: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$lock = new LockHandler('app:sendcoupons');
if (!$lock->lock()) {
$output->writeln('The command is already running in another process.');
return 0;
}
$em = $this->getContainer()->get('doctrine')->getManager();
$repo = $em->getRepository('AppBundle\\Entity\\Customer');
$customers = $repo->findBy(['isActivated' => true, 'couponsHaveBeenSent' => false], ['datetimeActivation' => 'ASC'], 100);
foreach ($customers as $customer) {
$mapped = $this->getContainer()->get('couponmapper')->mapNToCustomer(6, $customer);
if (!$mapped) {
$output->writeln('Could not map coupon codes to customer ' . $customer->getId());
$lock->release();
return 1;
}
$couponcodesData = [];
foreach ($customer->getCouponcodes() as $couponcode) {
ob_start();
@QRcode::png($couponcode->getCode());
$imageData = ob_get_contents();
ob_end_clean();
$couponcodesData[] = base64_encode($imageData);
}
$useRemoteFont = true;
if ($this->getContainer()->get('kernel')->getEnvironment() === 'test') {
$useRemoteFont = false;
// This decouples test runs from Internet connectivity
}
$pdfData = $this->getContainer()->get('knp_snappy.pdf')->getOutputFromHtml($this->getContainer()->get('templating')->render('AppBundle:coupons:index.html.twig', array('customer' => $customer, 'couponcodesData' => $couponcodesData, 'useRemoteFont' => $useRemoteFont)));
if ($this->getContainer()->get('kernel')->getEnvironment() === 'dev') {
file_put_contents('/var/tmp/coupon.pdf', $pdfData);
}
$fileLocator = $this->getContainer()->get('file_locator');
$brandsPdfPath = $fileLocator->locate('@AppBundle/Resources/other/Marken_Selbst_Vertragspartner_2015_09_24.pdf');
$message = \Swift_Message::newInstance()->setSubject('Ihre Rabattcodes für die Good Buy METRO Sonderaktion')->setFrom('goodbuy-metro@jumpmail.galeria-kaufhof.de')->setTo($customer->getEmail())->setBody($this->getContainer()->get('templating')->render('Emails/couponCodes.html.twig', ['customer' => $customer]), 'text/html')->attach(\Swift_Attachment::newInstance($pdfData, 'Goodbye-Metro-Rabattcodes.pdf', 'application/pdf'))->attach(\Swift_Attachment::fromPath($brandsPdfPath, 'application/pdf'));
$this->getContainer()->get('mailer')->send($message);
$customer->setCouponsHaveBeenSent(true);
$em->flush();
$output->writeln($customer->getEmail());
}
$lock->release();
}
示例14: notify
/**
* {@inheritdoc}
*/
public function notify(NotificationInterface $notification)
{
if (!class_exists('Swift_Message')) {
throw new \RuntimeException('You need to install swift mailer to use mailgun transport');
}
/** @var Email $notification */
$message = \Swift_Message::newInstance($notification->getSubject())->setFrom($notification->getFrom());
foreach ($notification->getParts() as $part) {
$message->attach(\Swift_MimePart::newInstance($part->getContent(), $part->getContentType()));
}
foreach ($notification->getAttachments() as $attachment) {
$message->attach(\Swift_Attachment::newInstance($attachment->getContent(), $attachment->getName(), $attachment->getContentType()));
}
$postData = ['o:tag' => $notification->getTags()];
foreach ($notification->getMetadata() as $key => $value) {
$postData['v:' . $key] = $value;
}
if ($recipientVariables = $notification->getRecipientVariables()) {
$postData['recipient-variables'] = json_encode($recipientVariables);
}
$failed = [];
$success = [];
$to = array_merge(array_values($notification->getTo()), array_values($notification->getCc()), array_values($notification->getBcc()));
if (!empty($to)) {
foreach (array_chunk($to, 1000) as $to_chunk) {
$result = new Result('mailgun', $this->getName());
$data = $postData;
$data['to'] = $to_chunk;
$res = $this->mailgun->sendMessage($this->domain, $data, $message->toString());
if ($res->http_response_code == 200) {
$success[] = $res;
} else {
$result->setResult(Result::FAIL);
$failed[] = $res;
}
$result->setResponse($res);
$notification->addResult($result);
}
if (count($success) === 0) {
throw new NotificationFailedException("Sending failed for message {$notification->getSubject()}", $failed);
}
}
}
示例15: interactionAction
/**
* Здесь мы получаем уведомления о статусе платежа и отмечаем платеж как успешный (или не отмечаем)
* Также рассылаем письма и билеты всем, кто был привязан к платежу
*
* @Route("/payment/interaction", name="payment_interaction")
* @Template()
*
* @param Request $request
*
* @return array
*/
public function interactionAction(Request $request)
{
/** @var Payment $payment */
$payment = $this->getDoctrine()->getRepository('StfalconPaymentBundle:Payment')->findOneBy(array('id' => $request->get('ik_pm_no')));
if (!$payment) {
throw new Exception('Платеж №' . $request->get('ik_pm_no') . ' не найден!');
}
// @var InterkassaService $interkassa
$interkassa = $this->container->get('stfalcon_event.interkassa.service');
if ($payment->isPending() && 1) {
//$interkassa->checkPayment($payment, $request)) {
$payment->markedAsPaid();
$em = $this->getDoctrine()->getManager();
$em->flush();
/** @var Ticket $ticket */
foreach ($payment->getTickets() as $ticket) {
// розсилка квитків
// @todo тут має смикатись сервіс який розсилає мильники про успішну оплату квитків + пдф в аттачі
$user = $ticket->getUser();
$event = $ticket->getEvent();
$twig = $this->get('twig');
// @todo ачуметь.. екшн в одному бандлі. вьюшка в іншому
$successPaymentTemplateContent = $twig->loadTemplate('StfalconEventBundle:Interkassa:success_payment.html.twig')->render(array('event_slug' => $event->getSlug()));
$mail = new Mail();
$mail->addEvent($event);
$mail->setText($successPaymentTemplateContent);
// Get base template for email
$emailTemplateContent = $twig->loadTemplate('StfalconEventBundle::email.html.twig');
$dateFormatter = new \IntlDateFormatter('ru-RU', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, 'd MMMM Y');
$text = $mail->replace(array('%fullname%' => $user->getFullName(), '%event%' => $event->getName(), '%date%' => $dateFormatter->format($event->getDate()), '%place%' => $event->getPlace()));
$body = $emailTemplateContent->render(array('text' => $text, 'mail' => $mail, 'add_bottom_padding' => true));
/** @var $pdfGen \Stfalcon\Bundle\EventBundle\Helper\PdfGeneratorHelper */
$pdfGen = $this->get('stfalcon_event.pdf_generator.helper');
$html = $pdfGen->generateHTML($ticket);
$outputFile = 'ticket-' . $event->getSlug() . '.pdf';
$message = \Swift_Message::newInstance()->setSubject($event->getName())->setFrom('orgs@fwdays.com', 'Frameworks Days')->setTo($user->getEmail())->setBody($body, 'text/html')->attach(\Swift_Attachment::newInstance($pdfGen->generatePdfFile($html, $outputFile), $outputFile));
$this->get('mailer')->send($message);
}
return new Response('SUCCESS', 200);
}
return new Response('FAIL', 400);
}