chicken burger
chicken burger

Reputation: 774

Send email through symfony 3 form

I tried the documentation on swiftmailer symfony here but I can't make it work even though it all seems correct to me.

I changed the paramaters.yml and didn't touch the config.yml as explained. It seems that the error comes from my controller, but in case I will copy you the code I have been writing/changing:

parameters.yml

    parameters:
        //
        mailer_host: localhost
        mailer_user: [email protected]
        mailer_password: mypassword

config.yml

swiftmailer:
    transport: '%mailer_transport%'
    host: '%mailer_host%'
    username: '%mailer_user%'
    password: '%mailer_password%'
    spool: { type: memory }

my form

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('mail', EmailType::class, array(
                'label' => 'your mail'
            ))
            ->add('message', TextareaType::class, array(
                'label' => 'your message'
            ))
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'    => Contact::class,
        ));
    }
}

My controller

    class MainController extends Controller
{
    public function indexAction(Request $request)
    {
        $contact = new Contact();
        $formContact = $this->createForm(ContactType::class, $contact);
        $formContact->handleRequest($request);
        $data = $formContact->getData();


        if ($formContact->isSubmitted() && $formContact->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $em->persist($contact);
            $em->flush();

            $message = \Swift_Message::newInstance();
            $message->setFrom($data->getMail())
                ->setTo('[email protected]')
                ->setBody($data->getMessage() . $data->getMail());

            $this->get('mailer')->send($message);
        }

        return $this->render('app/main/index.html.twig', array(
            'form' => $formContact->createView()
        ));
    }
}

An here is the error when I run this code enter image description here

I don't know if it helps or if you need more informatio but would be glad to share, thank you.

Upvotes: 0

Views: 371

Answers (1)

Darkstarone
Darkstarone

Reputation: 4730

Just to clarify Jenne's point: You need to use a getter method to access a private variable.

However, you're also using a spool in your config, so you need to actually access and fire off the spool once you've queued up a message. (See: here). If you don't want to spool, remove that line from your config, and emails should be sent directly from the code (Like shown in the tutorial).

Upvotes: 2

Related Questions