9951 explained code solutions for 126 technologies


php-swiftmailerHow to set an HTML body using Swiftmailer?


Using Swiftmailer, you can set an HTML body for an email message by using the setBody() method. This method takes a string argument which should contain the HTML code for the body of the email.

Example code

$message = (new \Swift_Message('My subject'))
  ->setFrom('[email protected]')
  ->setTo('[email protected]')
  ->setBody('<h1>Hello World!</h1>', 'text/html');

The code above will create a message with the subject "My subject" from "[email protected]" to "[email protected]" with an HTML body containing the text "Hello World!"

Parts of the code:

  • \Swift_Message('My subject'): creates a new Swift_Message object with the subject "My subject".
  • setFrom('[email protected]'): sets the sender of the message to "[email protected]".
  • setTo('[email protected]'): sets the recipient of the message to "[email protected]".
  • setBody('<h1>Hello World!</h1>', 'text/html'): sets the body of the message to the HTML code provided, with the content type set to "text/html".

Helpful links

Edit this code on GitHub