<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: sofiatarhonska</title>
    <description>The latest articles on DEV Community by sofiatarhonska (@sofiatarhonska_11).</description>
    <link>https://dev.to/sofiatarhonska_11</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F929467%2F54cc068e-b052-4831-90dd-2498eb7e25c6.png</url>
      <title>DEV Community: sofiatarhonska</title>
      <link>https://dev.to/sofiatarhonska_11</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sofiatarhonska_11"/>
    <language>en</language>
    <item>
      <title>Sending Emails in Laravel – All You Want to Know</title>
      <dc:creator>sofiatarhonska</dc:creator>
      <pubDate>Thu, 22 Sep 2022 12:41:37 +0000</pubDate>
      <link>https://dev.to/sofiatarhonska_11/sending-emails-in-laravel-all-you-want-to-know-375k</link>
      <guid>https://dev.to/sofiatarhonska_11/sending-emails-in-laravel-all-you-want-to-know-375k</guid>
      <description>&lt;p&gt;Many Mailtrap users create their apps with PHP and the vast majority of them choose Laravel. It is simple and in addition, is covered in-depth by documentation and tutorials. However, we still observe numerous questions on sending emails with Laravel, testing them, as well as Mailtrap configurations. We have analyzed the most popular requests on Stack Overflow, Reddit as well as Google search and in this post we will provide you with the list of answers. How to send an email with Laravel? How to send a &lt;a href="https://mailtrap.io/blog/laravel-mail-queue/" rel="noopener noreferrer"&gt;Laravel email&lt;/a&gt; via Mailtrap? Why isn’t Laravel mail working? Let’s figure it out. &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Laravel and how it works
&lt;/h2&gt;

&lt;p&gt;Laravel is a PHP framework that stands out for its simplicity, modernity, and connectivity. Probably, those characteristics make it especially popular among startups.&lt;/p&gt;

&lt;p&gt;Laravel is widely used for building websites, marketplaces, web apps, and even frameworks. &lt;/p&gt;

&lt;p&gt;The mail function is essential for these tasks, to register or notify the users, so it’s native  in Laravel and provides a wide range of capabilities: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A list of integrations for sending emails through local or cloud-based services.  Now Laravel proposes using drivers for &lt;a href="https://mailtrap.io/smtp-service/" rel="noopener noreferrer"&gt;SMTP&lt;/a&gt;, Mailtrap Email Delivery, Mailgun, SparkPost, Amazon SES, and sendmail.&lt;/li&gt;
&lt;li&gt;Options for queueing emails. &lt;/li&gt;
&lt;li&gt;Markdown support, which is available in a quite few frameworks. It lets you create beautiful templates and easily include buttons, tables, or panels. &lt;/li&gt;
&lt;li&gt;Regular plain text and HTML messages.&lt;/li&gt;
&lt;li&gt;Attaching files of different formats and MIME types, as well as raw data, inline attachments, and even embedding raw data into mail templates. &lt;/li&gt;
&lt;li&gt;Templating system, which lets you use various templates and configure the view. &lt;/li&gt;
&lt;li&gt;Message previews in-browser.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In addition, there are some noteworthy options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Localization methods, so that you can set the desired language for a specific user.&lt;/li&gt;
&lt;li&gt;Local development mailing. This is how you can prevent sending test emails to real inboxes. &lt;a href="https://mailtrap.io/" rel="noopener noreferrer"&gt;Mailtrap&lt;/a&gt; is one of the preferred options.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What you need to know about Laravel Mail
&lt;/h2&gt;

&lt;p&gt;You will intuitively find all guidelines on the &lt;a href="https://laravel.com/" rel="noopener noreferrer"&gt;Laravel&lt;/a&gt; website and the educational &lt;a href="https://laracasts.com/browse/all" rel="noopener noreferrer"&gt;Laracasts&lt;/a&gt; portal. That is why we rejected the idea of creating our own tutorial. For a better understanding, we decided to outline some basic principles, provide you with examples of creating an email in Laravel, and give you some tips and explanations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Building email in Laravel
&lt;/h3&gt;

&lt;p&gt;Here are a couple of basic things to keep in mind.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Laravel includes its own command-line interface called &lt;code&gt;Artisan&lt;/code&gt;. (Yes, it definitely refers to their slogan “The PHP framework for web artisans”). It provides a bundle of useful commands, for email creation in particular. To get all available commands, type:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Each email category can be represented as a “mailable”. It’s a class that is responsible for building a specific email message using a set of methods.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:mail NewUserNotification

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;command generates a class, which you’ll find at &lt;em&gt;‘app/Mail/NewUserNotification.php&lt;/em&gt;. The build() method of this class creates email messages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function build()
{
    return $this-&amp;gt;from('example@example.com')
        -&amp;gt;view('emails.newuser');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way, we have written a mailable with a &lt;code&gt;build()&lt;/code&gt; method. Of course, it’s a minimal example, but you can make the necessary configuration and the next time you need to send it again, you will just type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mail::to($emailAddress)-&amp;gt;send(new NewUserNotification);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Mailables were introduced in Laravel 5.3.&lt;/p&gt;

&lt;h3&gt;
  
  
  Sending an email in Laravel
&lt;/h3&gt;

&lt;p&gt;To send an email, you have a bunch of options. Laravel’s creators recommend using one of the &lt;strong&gt;API based drivers&lt;/strong&gt;: Mailgun, SparkPost, or Amazon SES.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Laravel 7.0&lt;/strong&gt; introduces multiple drivers. It means that you can set one of the drivers as a default one in your mail configuration file (Mailgun, for example), but configure sending particular types of messages (let’s say, notifications) with SparkPost.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mail::mailer('sparkpost')
        -&amp;gt;to($emailAddress())
        -&amp;gt;send(new NewUserNotification));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For configurations, follow &lt;a href="https://laravel.com/docs/7.x/mail#driver-prerequisites" rel="noopener noreferrer"&gt;this section&lt;/a&gt; of the Laravel Documentation.&lt;/p&gt;

&lt;p&gt;You are also free to use any &lt;strong&gt;SMTP server&lt;/strong&gt; you prefer, like Gmail. The related configurations are made in the config/mail.php file. In the default Laravel setup, the email configuration is read from environment variables so to edit them, you should save your changes to the .env file (you will find it in the root directory).&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://mailtrap.io/blog/" rel="noopener noreferrer"&gt;Mailtrap SMTP server&lt;/a&gt; is one of the recommended &lt;a href="https://mailtrap.io/smtp-service/" rel="noopener noreferrer"&gt;SMTP&lt;/a&gt; methods in Laravel. It helps you avoid sending test emails to real inboxes by accident. It is designed to catch these interim emails and help you debug them. With Mailtrap, your &lt;strong&gt;email will never&lt;/strong&gt; land in the &lt;strong&gt;real inbox&lt;/strong&gt; in any of the email clients.&lt;/p&gt;

&lt;p&gt;So, if you are ready to send your message to your own or even your customer’s inbox, don’t forget to replace the configuration with that of the real server. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=your password
MAIL_ENCRYPTION=ssl

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And if you’re using &lt;a href="https://mailtrap.io/email-api/" rel="noopener noreferrer"&gt;Mailtrap Email Delivery&lt;/a&gt; as your sending solution, we provide the &lt;a href="https://mailtrap.io/blog/setup-smtp-server/" rel="noopener noreferrer"&gt;SMTP configuration&lt;/a&gt; for you. Just copy-paste the configuration listed in the app, verify your domain, and you’re good to go.&lt;/p&gt;

&lt;h2&gt;
  
  
  Laravel versions
&lt;/h2&gt;

&lt;p&gt;A new version of Laravel is released every six months. Then bug fixes are provided for another six months while security fixes are delivered within a year. Also, starting from 5.1, Laravel offers long-term support (LTS) version, with bug fixes valid for two years and security fixes – for three. &lt;/p&gt;

&lt;p&gt;For July 2020, Laravel 7.0 is the latest released version. &lt;/p&gt;

&lt;p&gt;We observe that in 2020 users were still working with Laravel 6.2, 5.8, 5.6, 5.4, 5.3, or even 5.2 versions. But versions below 5.5 (LTS) were no longer supported: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9ge38r2zdzlydo9jebnx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9ge38r2zdzlydo9jebnx.png" alt="Laravel versions"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Source: &lt;a href="https://laravel.com/docs/master/releases" rel="noopener noreferrer"&gt;https://laravel.com/docs/master/releases&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Sometimes, the use of the old versions might result in some performance issues. Most likely, you might just miss some functionality and waste your time. Here is a list of some important updates delivered in 6 and 7 versions, which affect email sending options.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Laravel 6 (LTS)&lt;/strong&gt; introduced semantic versioning, compatibility with Laravel Vapor, enhanced authorization responses, job middleware, lazy collections, and subquery improvements, as well as other bug fixes and usability improvements.&lt;/p&gt;

&lt;p&gt;Laravel 7 delivered Laravel Sanctum (an authentication system), Blade component tags, a developer-focused HTTP client, first-party CORS support, multiple mail drivers, a new artisan test command, along with other bug fixes and usability improvements.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to send email in Laravel 7.0 using SMTP
&lt;/h2&gt;

&lt;p&gt;To sum up, let’s review an example of coding a message in Laravel 7.0 and testing it with Mailtrap’s fake SMTP service. We will take advantage of Laravel’s awesome features like Blade templates, Mailable class, and Markdown support.&lt;/p&gt;

&lt;p&gt;We assume that you have been already using Laravel for building your application. If you were working in one of the previous versions, update your &lt;code&gt;laravel/framework&lt;/code&gt; dependency to &lt;code&gt;7.0.*&lt;/code&gt; in your &lt;em&gt;composer.json&lt;/em&gt; file, as recommended in the official guide.&lt;/p&gt;

&lt;p&gt;Let’s start by defining an SMTP server and setting the mailing configuration. We prefer to test our notifications with Mailtrap first, to make sure our code works fine and the content of the messages is rendered properly.&lt;/p&gt;

&lt;p&gt;Mailtrap is a default server in Laravel, so you need just to type in your credentials. You will find them in the SMTP Settings tab of your Inbox. Also, you can use Integrations data from the same tab. Choose Laravel from the list, copy the following details, and paste them to your &lt;em&gt;.env&lt;/em&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=1a2b3c4d5e6f7g //your username
MAIL_PASSWORD=1a2b3c4d5e6f7g // your password
MAIL_FROM_ADDRESS=from@example.com
MAIL_FROM_NAME=Example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s move to the CLI:&lt;br&gt;
&lt;code&gt;php artisan make:mail MailtrapExample&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This way, we have created a Mailable class, with the name &lt;code&gt;MailtrapExample.php&lt;/code&gt;. Now we should find it in the Mail directory in &lt;code&gt;app/Mail&lt;/code&gt;. We have a template, which contains basic needed functions so that we should just modify it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MailtrapExample extends Mailable
{
    use Queueable, SerializesModels;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Build the message.
     *
     * @return $this
     */
public function build()
    {
        return $this-&amp;gt;from('mail@example.com', 'Mailtrap')
            -&amp;gt;subject('Mailtrap Confirmation')
            -&amp;gt;markdown('mails.exmpl')
            -&amp;gt;with([
                'name' =&amp;gt; 'New Mailtrap User',
                'link' =&amp;gt; '/inboxes/'
            ]);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We’ve added a sender, a subject, a couple of variables and introduced the Markdown support.&lt;/p&gt;

&lt;p&gt;Now it’s time to create the body of our message. For this purpose, we will use a Blade template.&lt;/p&gt;

&lt;p&gt;We have specified that our mailable is located in the &lt;code&gt;mails.exmpl&lt;/code&gt;. Now we need to create a ‘mails’ directory with a blade template file ‘exmpl.blade.php’. inside. Templates represent views in Laravel, so keep the template file in the resources/views/mails directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@component('mail::message')
Hello **{{$name}}**,  {{-- use double space for line break --}}
Thank you for choosing Mailtrap!
Click below to start working right now
@component('mail::button', ['url' =&amp;gt; $link])
Go to your inbox
@endcomponent
Sincerely,
Mailtrap team.
@endcomponent
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our simple configuration is done, and we can move forward with sending our message. Specify the route in the &lt;em&gt;routes/web.php&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
use App\Mail\MailtrapExample;
use Illuminate\Support\Facades\Mail;
Route::get('/send-mail', function () {
    Mail::to('newuser@example.com')-&amp;gt;send(new MailtrapExample());
    return 'A message has been sent to Mailtrap!';
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run your application. Usually, it should be &lt;code&gt;php artisan serve&lt;/code&gt; in development, then go to /send-mail path of your application in the browser (&lt;a href="http://127.0.0.1:8000/send-mail" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/send-mail&lt;/a&gt; when running with &lt;code&gt;php artisan serve&lt;/code&gt;.) &lt;/p&gt;

&lt;p&gt;Note that starting from the 5.8 version, Laravel is capable of serving multiple applications. Earlier, only port 8000 was available but now serves scans for free options up to 8009. &lt;/p&gt;

&lt;p&gt;That’s it. Your application will send a message and you will see it in your Mailtrap inbox:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk23ezcxj42368q56zbod.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk23ezcxj42368q56zbod.jpeg" alt="new-mailtrap-confirmation"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Verify if the result matches your expectations: whether all elements are displayed correctly and links work properly. View the &lt;strong&gt;Check HTML&lt;/strong&gt; and &lt;strong&gt;Analysis&lt;/strong&gt; tabs in Mailtrap to make sure your messages won’t be considered spam and will be rendered correctly in most email clients.&lt;/p&gt;

&lt;p&gt;Once you are satisfied with the results of tests, replace SMTP configurations with your production server or configure any other option to send emails to real inboxes.&lt;/p&gt;




&lt;p&gt;Here we go! I hope you've got a good time reading our guide on &lt;a href="https://mailtrap.io/blog/send-email-in-laravel" rel="noopener noreferrer"&gt;sending emails in Laravel to multiple recipients&lt;/a&gt;, initially published in the Mailtrap blog. &lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>How to Send Emails from Spring Boot App</title>
      <dc:creator>sofiatarhonska</dc:creator>
      <pubDate>Wed, 21 Sep 2022 14:06:06 +0000</pubDate>
      <link>https://dev.to/sofiatarhonska_11/how-to-send-emails-from-spring-boot-app-57lf</link>
      <guid>https://dev.to/sofiatarhonska_11/how-to-send-emails-from-spring-boot-app-57lf</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;This article is a step-by-step guide on how to create a landing page that sends a welcome email to subscribers. This will be developed with Java and Spring Boot. It will also show all the required processes for the download of tools and the test for running the web application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Tools
&lt;/h2&gt;

&lt;p&gt;Starting any application with Spring is a good way to use Spring Tools as it improves the IDEs and brings features to facilitate the codification. This article will be using the Spring Tool 4 for Eclipse on Mac OS. However, it’s also available for Visual Studio Code and Theia, and it can be downloaded from &lt;a href="https://spring.io/tools"&gt;Spring Tools&lt;/a&gt;. Choose which one is better for you and download it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Initializr
&lt;/h2&gt;

&lt;p&gt;Another useful tool for starting a Spring Boot project is the Spring Initializr (&lt;a href="https://start.spring.io/"&gt;https://start.spring.io/&lt;/a&gt;), which has a web interface where the configuration of the project can be set up and the dependencies can be chosen. After filling out the form, the project can be downloaded and imported from Spring Tools with the Import Spring Getting Started Content option.&lt;/p&gt;

&lt;p&gt;Another way to create a Spring project is using Spring Tools, which provides a feature called Create a New Spring Starter Project. It’s a wizard with the same options available on the web interface.&lt;/p&gt;

&lt;p&gt;This article will be using a Gradle Project with Java 15. The dependencies used are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring Web (allows running web application on Apache Tomcat and, because of this, the packaging needs to be a War format)&lt;/li&gt;
&lt;li&gt;Java Mail Sender (include the dependencies for sending email)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The image below shows the Spring Initializr form filled out to guide you. Note that the Group field represents the project packages and must be filled with com.domain.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IIwcP3Tg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djgt0wzchfc6ug8wg5y3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IIwcP3Tg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djgt0wzchfc6ug8wg5y3.png" alt="sending emails with spring" width="880" height="906"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After filling, click on the GENERATE button to download your initialized project. Then, open Spring Tools and click on Import Spring Getting Started Content to open your downloaded project.&lt;/p&gt;

&lt;p&gt;If you prefer to do this directly on Spring Tools, click on Create New Spring Starter Project. In the window, the New Spring Starter Project fills the text inputs with the full name and description and chooses the options listed below.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Type: Gradle&lt;/li&gt;
&lt;li&gt;Packaging: War&lt;/li&gt;
&lt;li&gt;Java Version: 15&lt;/li&gt;
&lt;li&gt;Language: Java&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Click on Next and choose the dependencies Spring Web and Java Mail Sender. Now, just click Finish to create your project.&lt;/p&gt;

&lt;h2&gt;
  
  
  Gradle Configuration
&lt;/h2&gt;

&lt;p&gt;A project created with the wizard on Spring Initializr or on Spring Tools will have the build.gradle file filled with the configurations that the project needs to run. Check if your build.gradle has the Thymeleaf as dependencies, it will be necessary to associate the pages with the model in the next steps.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;plugins {
id 'org.springframework.boot' version '2.5.0-SNAPSHOT'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
        id 'java'
id 'war'
}

group = 'com.domain'
version = '0.0.1'
sourceCompatibility = '15'

repositories {
mavenCentral()
        maven { url 'https://repo.spring.io/milestone' }
        maven { url 'https://repo.spring.io/snapshot' }
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
        implementation 'org.springframework.boot:spring-boot-starter-mail'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
useJUnitPlatform()
}

springBoot {
mainClassName = 'com.domain.landing.LandingApplication'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Creating a Landing Page&lt;br&gt;
In the LandingApplication.java file, we will define the listener on our web application. It is basically a class with a main method and @SpringBootApplication. This class will create the ApplicationContext and launch the web application. Inside the main method, we need to call run from SpringApplication to start it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// LandingApplication.java
package com.domain.landing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LandingApplication {
    public static void main(String[] args) {
     SpringApplication.run(LandingApplication.class, args);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Model Structure
&lt;/h2&gt;

&lt;p&gt;The class model will be used to store the name and email used in the form. These pieces of information will navigate across the controller and mailer. We need to create a new package to put the model in. Usually, the package will have the model and the controller separating the code by subjects. Following this package structure helps the Spring Boot to scan and find the classes. Another way is to separate a package for models and another for controllers – this is also a valid approach.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SubscribeForm.java
package com.domain.landing.subscribe;

public class SubscribeForm {
    private String name;
    private String email;

    public String getName() {
     return this.name;
    }

    public void setName(String name) {
     this.name = name;
    }

    public String getEmail() {
     return this.email;
    }

    public void setEmail(String name) {
     this.email = name;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Controller and Requests&lt;br&gt;
The first version of our controller implements two routes: GET and POST methods. A method called showForm will receive a subscribe object and mapping to render the form page. This page will have a form with fields for name and email, and also a Submit button. This submits our second method submitForm, which also receives the subscribing object as a parameter. For now, this method will only redirect to the successful subscribe page.&lt;/p&gt;

&lt;p&gt;It’s important to highlight that the addViewControllers method is necessary for registering the view that will be used for redirection with the POST method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SubscribeController.java
package com.domain.landing.subscribe;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Controller
public class SubscribeController implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/subscribe/confirmation").setViewName("subscribe/confirmation");
}

@GetMapping("/")
public String showForm(SubscribeForm subscribeForm) {
return "/subscribe/form";
}

@PostMapping("/")
public String submitForm(SubscribeForm subscribeForm) {
return "redirect:/subscribe/confirmation";
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Views Files
&lt;/h2&gt;

&lt;p&gt;In the src/main/resources/templates package, we’ll create a package called Subscribe to store our HTML files for our views and pages. The form.html file will contain the form and will be the page shown when accessed.&lt;/p&gt;

&lt;p&gt;Note that the object has to be the same name as your parameter on the submitForm and the action must be the same as defined on PostMapping.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main/resources/templates/subscribe/form.html
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;title&amp;gt;Subscribe on newsletter&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
        &amp;lt;h1&amp;gt;Subscribe on newsletter&amp;lt;/h1&amp;gt;
        &amp;lt;form action="#" th:action="@{/}" th:object="${subscribeForm}" method="post"&amp;gt;
                &amp;lt;table&amp;gt;
                &amp;lt;tr&amp;gt;
                            &amp;lt;td&amp;gt;Name:&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;&amp;lt;input type="text" th:field="*{name}" /&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                    &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;Email:&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;&amp;lt;input type="text" th:field="*{email}" /&amp;gt;&amp;lt;/td&amp;gt;
                    &amp;lt;/tr&amp;gt;
                &amp;lt;tr&amp;gt;
                        &amp;lt;td&amp;gt;&amp;lt;button type="submit"&amp;gt;Subscribe&amp;lt;/button&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/table&amp;gt;
            &amp;lt;/form&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The confirmation.html file has only a message informing us that everything works. This will be shown after submitting the form.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// confirmation.html
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta charset="UTF-8"&amp;gt;
&amp;lt;title&amp;gt;Subscribe on newsletter&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;h1&amp;gt;Successfully subscribed!&amp;lt;/h1&amp;gt;
&amp;lt;h2&amp;gt;You will receive an email confirming your subscription.&amp;lt;/h2&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Testing so Far&lt;br&gt;
Start your application by clicking on the Run button, or open a terminal, go to the project directory, run ./gradlew bootRun on the terminal, and access the URL &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt; – it’ll show a page similar to the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--46Kne2Xv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tuaoiom864uh8gzg6i9l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--46Kne2Xv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tuaoiom864uh8gzg6i9l.png" alt="sending emails with spring" width="694" height="302"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fill out the form and click on the Subscribe button to see the redirect in action and the confirmation page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--djaV_nfU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5u02xmy38qz6wk7otwj9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--djaV_nfU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5u02xmy38qz6wk7otwj9.png" alt="sending emails with spring" width="880" height="163"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you see this, you can move forward, so let’s implement the sending email.&lt;/p&gt;
&lt;h2&gt;
  
  
  Sending Emails to Mailtrap Testing Environment
&lt;/h2&gt;

&lt;p&gt;To test our sending emails, we’ll use Mailtrap. Mailtrap is a service for inspecting the email content received before sending it in production. Mailtrap is free for personal side projects, so we can send 500 emails per month and test our application in development and even staging environments.&lt;/p&gt;

&lt;p&gt;To start using Mailtrap access &lt;a href="https://mailtrap.io/"&gt;https://mailtrap.io/&lt;/a&gt; home page, create your account, and log in to it.&lt;/p&gt;

&lt;p&gt;On the sidebar, access the Testing &amp;gt; Inboxes menu. In the shows Projects panel, click on Add Inbox.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6g_F3Etx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evg6h2dv5rf7y18lpr62.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6g_F3Etx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evg6h2dv5rf7y18lpr62.png" alt="sending emails with spring" width="880" height="162"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fill the Inbox name field with a meaningful name, such as Subscribers, and then click on the Save button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lWV-gui_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7fwhmsiwx9zwpr33lx6o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lWV-gui_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7fwhmsiwx9zwpr33lx6o.png" alt="mailtrap testing" width="880" height="160"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now click on Subscribers to access the configuration page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oB0vH05F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yzcfy69bjs4u79q407d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oB0vH05F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yzcfy69bjs4u79q407d.png" alt="mailtrap testing" width="880" height="138"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on Show Credentials to see the SMTP information required to send the email. This information will be added to the Properties in our Mail class.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8oW5Tw1M--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/euhlgl7o0344b2gj82ow.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8oW5Tw1M--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/euhlgl7o0344b2gj82ow.png" alt="mailtrap testing tool" width="880" height="200"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We also need to get the email used as the sender. To get this, click on the Email Address tab and copy the Inbox Email Address.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YeKuoVVb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69pv647qarbuwweoqzy0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YeKuoVVb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69pv647qarbuwweoqzy0.png" alt="sending emails with spring" width="880" height="153"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Create a new package called Mailer and a new class called Mail. In this class, create constants to store the configuration that you got from Mailtrap. The setProperties method assigns the constants to the Properties object that will be used to create a session authentication with Mailtrap credentials.&lt;/p&gt;

&lt;p&gt;The send method creates a message with email fields such as from, recipient, subject, content, and date. The send method of Transport class is responsible for sending the message to Mailtrap inbox.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Mail.java
package com.domain.landing.mailer;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.domain.landing.subscribe.SubscribeForm;

public class Mail {
        private final String PORT = "587";
        private final String HOST = "smtp.mailtrap.io";
        private final String USERNAME = "bb817095de807a";
        private final String PASSWORD = "e625767e122812";
        private final String EMAIL = "0b5d29e626-65f490@inbox.mailtrap.io";

        private final boolean AUTH = true;
        private final boolean STARTTLS = true;

        public void send(SubscribeForm subscriber) throws AddressException, MessagingException, IOException {
Message msg = new MimeMessage(setSession(setProperties()));

        msg.setSentDate(new Date());
            msg.setSubject("You're subscribed on newsletter");

msg.setFrom(new InternetAddress(EMAIL, false));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(subscriber.getEmail()));

        msg.setContent(subscriber.getName().concat(", you're very welcome here!"), "text/html");

Transport.send(msg);
    }

private Session setSession(Properties props) {
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USERNAME, PASSWORD);
                }
});
        return session;
}

private Properties setProperties() {
        Properties props = new Properties();

    props.put("mail.smtp.port", PORT);
            props.put("mail.smtp.host", HOST);
    props.put("mail.smtp.auth", AUTH);
            props.put("mail.smtp.starttls.enable", STARTTLS);

        return props;
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With Mail class created, we need to call the send method when the form was submitted. To do this, create a new instance from Mail in the submitForm method on SubscribeController. This instance will call the send method to pass the subscribe as a parameter. This parameter contains the email and name used to mount the email that will be sent. It’ll throw AddressException, MessagingException and IOException exceptions, and will also need to import these packages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SubscribeController.java
...
import com.domain.landing.mailer.Mail;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
...

@Controller
public class SubscribeController implements WebMvcConfigurer {
...
@PostMapping("/")
        public String submitForm(SubscribeForm subscribeForm) throws AddressException, MessagingException, IOException {
Mail mailer = new Mail();
mailer.send(subscribeForm);
return "redirect:/subscribe/confirmation";
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the application again, access &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;, fill the form and click on the Subscribe button. Go back to Mailtrap and access Inboxes &amp;gt; Subscribers to see the received email.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6RCZhTZO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1oe5a7qqwiuohibd24l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6RCZhTZO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1oe5a7qqwiuohibd24l.png" alt="sending html email using java spring" width="880" height="96"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending Emails with Attachments
&lt;/h2&gt;

&lt;p&gt;Now let’s try sending emails with attachments. Add an image to src/main/resources/static. In my case, I used an image called fine.jpeg.&lt;/p&gt;

&lt;p&gt;We need to change the content of the email body to work with multipart to add the message and the attachment. The multipart instance will be initialized on the Mail constructor and will be accessed by the receiver. Two new methods were created: the setMessage to include the multipart as content and the setAttachment to attach the file. After adding this body’s parties to multipart, we can set the multipart as the content of the MimeMessage instance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import java.io.File;
...

import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
...

public class Mail {
    ...
private Multipart multipart;

public Mail() {
this.multipart = new MimeMultipart();
}

private Multipart getMultipart() {
     return multipart;
}

public void send(SubscribeForm subscriber) throws AddressException, MessagingException, IOException {
Message msg = new MimeMessage(setSession(setProperties()));

        setAttachment();
            setMessage(subscriber);

            msg.setContent(getMultipart());
            msg.setSentDate(new Date());
            msg.setSubject("You're subscribed on newsletter");

            msg.setFrom(new InternetAddress(EMAIL, false));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(subscriber.getEmail()));

Transport.send(msg);
}

private void setMessage(SubscribeForm subscriber) throws MessagingException {
MimeBodyPart message =  new MimeBodyPart();

message.setContent(subscriber.getName().concat(", you're very welcome here!"), "text/html");

        getMultipart().addBodyPart(message);
}

private void setAttachment() throws MessagingException, IOException {
        MimeBodyPart attachment = new MimeBodyPart();

attachment.attachFile(new File("src/main/resources/static/fine.jpeg").getCanonicalPath());

        getMultipart().addBodyPart(attachment);
}
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Re-run the application, access &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;, fill out the form, and click on the Subscribe button. Go back to Mailtrap and access Inboxes &amp;gt; Subscribers to view the received email with the attachment. You can download it to check whether the image arrived without any issues. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w0d13tpt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqfd6osn672sceq5htij.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w0d13tpt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqfd6osn672sceq5htij.png" alt="sending html email using java spring" width="880" height="96"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending HTML Email
&lt;/h2&gt;

&lt;p&gt;When we set the content, we can parse the type of our content. In the example above, we are already parsing text/html as a type. Using this configuration, we can parse any HTML code inside a string and send the email with HTML formatting. Something like this will work and send a formatted email.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
public Mail() {
...
private void setMessage(SubscribeForm subscriber) throws MessagingException {
        MimeBodyPart message =  new MimeBodyPart();

    String content = "&amp;lt;h1&amp;gt;" + subscriber.getName() + "&amp;lt;/h1&amp;gt;&amp;lt;br /&amp;gt;";
    message.setContent(content + ", you're very welcome here!", "text/html");

        getMultipart().addBodyPart(message);
        }
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But we can improve it using StringBuffer to create a string with all the content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
public Mail() {
…
private void setMessage(SubscribeForm subscriber) throws MessagingException {
        MimeBodyPart message =  new MimeBodyPart();

    StringBuffer htmlContent = new StringBuffer();
            htmlContent.append("&amp;lt;html&amp;gt;&amp;lt;head&amp;gt;&amp;lt;style&amp;gt;");
        htmlContent.append("body { background-color: #f2f2f2; }");
        htmlContent.append("h1 { color: #333; }");
        htmlContent.append("&amp;lt;/style&amp;gt;&amp;lt;/head&amp;gt;&amp;lt;body&amp;gt;&amp;lt;h1&amp;gt;");
        htmlContent.append(subscriber.getName());
        htmlContent.append(", you're very welcome here!");
        htmlContent.append("&amp;lt;/h1&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;");

message.setContent(htmlContent.toString(), "text/html");

    getMultipart().addBodyPart(message);
}
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another more sophisticated option is to use some templates for our email and pass the variable as a parameter to the HTML file. Some options that work well with Spring Boot are Thymeleaf and FreeMaker.&lt;/p&gt;

&lt;p&gt;One more time, run the application, access &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;, fill out the form, and click on the Subscribe button. Go back to Mailtrap and access Inboxes &amp;gt; Subscribers to see the received email with HTML and CSS formatting.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--n-Z6VfcI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3s3klr31uoml0a0rwc5w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n-Z6VfcI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3s3klr31uoml0a0rwc5w.png" alt="sending html email using java spring" width="880" height="96"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on the HTML Source tab to see the generated HTML.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--j8KPi7r2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjoiwqmmpxmmf72nlhat.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--j8KPi7r2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjoiwqmmpxmmf72nlhat.png" alt="sending email java spring" width="880" height="81"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another awesome feature of Mailtrap is showing whether the HTML and CSS in our email are valid in the email clients. Click on the Check HTML tab to verify the errors.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RbwB-lPi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hh0ohmz3mlwjiyxzjasw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RbwB-lPi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hh0ohmz3mlwjiyxzjasw.png" alt="send email in java spring" width="880" height="107"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Conclusion&lt;br&gt;
There are other ways to send an email with Spring Boot. With fewer changes, we can, for example, move the authentication constants from Mail class to the application.properties. We can also use some templates to improve the HTML emails. It’s important to see other possibilities to refactor and grow our code. Did you see something to improve here? Let’s talk!&lt;/p&gt;

&lt;p&gt;I hope you’ve had a good time reading our guide on &lt;a href="https://mailtrap.io/blog/spring-send-email/"&gt;how to send emails to multiple recipients with Java Spring&lt;/a&gt;, which was originally published in the Mailtrap Blog!&lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>email</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Send and Receive Emails in ASP.NET C#</title>
      <dc:creator>sofiatarhonska</dc:creator>
      <pubDate>Tue, 20 Sep 2022 12:57:46 +0000</pubDate>
      <link>https://dev.to/sofiatarhonska_11/send-and-receive-emails-in-aspnet-c-4hk1</link>
      <guid>https://dev.to/sofiatarhonska_11/send-and-receive-emails-in-aspnet-c-4hk1</guid>
      <description>&lt;p&gt;You’ve got a long ASP.NET project ahead. You’re trying to wrap your head around all tasks at hand – infrastructure, business logic, admin panel, integrations. On top of that, there’s a long list of &lt;a href="https://railsware.com/blog/moscow-prioritization/"&gt;‘could have’ type&lt;/a&gt; of features that the team would like to implement if time and resources allow.&lt;/p&gt;

&lt;p&gt;One of them is adding the ability to send an email in ASP.NET C# that you’ve been postponing for a while. After all, it’s such an obvious feature that might as well be left for the very end, when almost everything is up and running. Before your project goes live, you will need to validate your email workflows anyway and probably you don’t want to stay extra hours just before the launch to do so.&lt;/p&gt;

&lt;p&gt;While sending emails with C# is not rocket science, we strongly recommend thinking about it sooner rather than later. To make it easier to start, we’ve covered the first steps with the various code samples. Let’s start!&lt;/p&gt;

&lt;h2&gt;
  
  
  MailMessage
&lt;/h2&gt;

&lt;p&gt;Throughout the course of this article, we’ll often be using &lt;code&gt;MailMessage&lt;/code&gt; class. It’s a part of &lt;code&gt;System.Net.Mail&lt;/code&gt; namespace and is used to create email messages that are then sent to an SMTP server. The delivery is then taken care of by the &lt;code&gt;SmtpClient&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;For the complete set of parameters of this class, please refer to &lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8"&gt;Microsoft’s documentation&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending emails in C# with &lt;a href="https://mailtrap.io/smtp-service/"&gt;SMTP&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;This one is fairly easy and quick to set up as SMTP (&lt;a href="https://mailtrap.io/blog/smtp/"&gt;Simple Mail Transfer Protocol&lt;/a&gt;) is the most common communication standard used in email transmission. In the example below, we’ll show how to send a very simple email with the following details:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To:&lt;/strong&gt; &lt;em&gt;&lt;a href="mailto:elizabeth@westminster.co.uk"&gt;elizabeth@westminster.co.uk&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;From:&lt;/strong&gt; &lt;em&gt;&lt;a href="mailto:piotr@mailtrap.io"&gt;piotr@mailtrap.io&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Title:&lt;/strong&gt; &lt;em&gt;Good morning, Elizabeth&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Body:&lt;/strong&gt; &lt;em&gt;Elizabeth, Long time no talk. Would you be up for lunch in Soho on Monday? I’m paying.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In order to send such an email, we’ll use the aforementioned &lt;code&gt;MailMessage&lt;/code&gt; class from .NET API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning, Elizabeth";
message.Body = "Elizabeth, Long time no talk. Would you be up for lunch in Soho on Monday? I'm paying.;";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
    Credentials = new NetworkCredential("smtp_username", "smtp_password"),
    EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the message was configured, we connected to the SMTP server and sent it &lt;a href="https://www.youtube.com/watch?v=5tKtVuT-MGE"&gt;this way&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;Mailtrap &lt;a href="https://mailtrap.io/blog/email-deliverability/"&gt;Email Delivery&lt;/a&gt; also allows you to send emails via SMTP. Just verify your domain, copy the provided SMTP settings to your app or service, and start sending to your recipients.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending emails with attachments
&lt;/h2&gt;

&lt;p&gt;Now that we know how to send basic emails, let’s consider a very common scenario and add an attachment to our message to the Queen of England. This could be an invoice for the last royal wedding or a set of pictures we took on that fabulous weekend.&lt;/p&gt;

&lt;p&gt;On top of &lt;code&gt;MailMessage&lt;/code&gt; class, we’ll use &lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.attachment?view=netframework-4.8"&gt;Attachment class&lt;/a&gt; from .NET API. Make sure you add the attachment to the current working directory first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
String filePath = "wedding_invoice.pdf";
Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet);
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Regarding our meeting";
message.Body = "Elizabeth, as requested, sending you the invoice for Harry and Meghan's wedding. Any questions? Let me know.;";
message.Attachments.Add(data);
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
    Credentials = new NetworkCredential("smtp_username", "smtp_password"),
    EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you need to send multiple invoices (lucky you!) or other files, simply use a loop and add the other files to the email.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding images inline
&lt;/h2&gt;

&lt;p&gt;We’ve just covered sending emails with attachments. But what if you’re sending images but want them displayed inline rather than being attached to an email. Certainly, it will be easier to attract the Queen’s attention this way. With a bit of modification of our previous code, this can be easily achieved.&lt;/p&gt;

&lt;p&gt;When trying to send an email with images in C#, you’re not going to use a typical &lt;code&gt;&amp;lt;img src="" alt="" /&amp;gt;&lt;/code&gt; construction. It would add an image attachment to the email and that’s the last thing we need right now. Instead, we’ll use &lt;code&gt;LinkedResource&lt;/code&gt; object to directly embed an image in the HTML version of our message to the Queen. We will then follow our regular approach with &lt;code&gt;MailMessage&lt;/code&gt; class. As always, remember to upload the file first to your current working directory. If it’s missing, an email will be sent without any attachment and, really, aren’t we receiving these “oops, forgot about the attachment!” emails too often already?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
String messageBody = "Elizabeth, sending you a quick sneak peak of the pictures" +
  "we took at the last royal wedding. " +
  "Let me know your thoughts.";
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Pics from the royal wedding";
message.Body = messageBody;
String imagePath = "bestpictureever.png";
LinkedResource LinkedImage = new LinkedResource(@imagePath);
LinkedImage.ContentId = "Wedding";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  $"{messageBody} &amp;lt;br&amp;gt; &amp;lt;img src=cid:Wedding&amp;gt;", null, "text/html"
);
htmlView.LinkedResources.Add(LinkedImage);
message.AlternateViews.Add(htmlView);
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Sending to multiple recipients
&lt;/h2&gt;

&lt;p&gt;Let’s say we want to use the opportunity and remind the Queen and her grandson about unpaid invoices.&lt;/p&gt;

&lt;p&gt;No rocket science here either. New recipients are simply added to the code, separated by a comma. As in the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
    Credentials = new NetworkCredential("smtp_username", "smtp_password"),
    EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Things get a tiny bit more tricky when you want to add people in bcc and cc, we’ll need a few additional lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
message.CC.Add(new MailAddress("meghan@westminster.co.uk"));
message.Bcc.Add(new MailAddress("charles@westminster.co.uk"));
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
    Credentials = new NetworkCredential("smtp_username", "smtp_password"),
    EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Voila!&lt;/p&gt;

&lt;h2&gt;
  
  
  Do I need to have an &lt;a href="https://mailtrap.io/smtp-service/"&gt;SMTP&lt;/a&gt; server?
&lt;/h2&gt;

&lt;p&gt;Let’s consider a situation when you don’t have (or don’t want to have) an SMTP server configured but still want to send an email in C#.&lt;/p&gt;

&lt;p&gt;The first option is to do a DNS MX lookup of the email address that you’re trying to send an email to. This allows you to figure out what the SMTP server is and connect to it. So, you’re still going to use an SMTP server, just not yours!&lt;/p&gt;

&lt;p&gt;We don’t, however, recommend such an approach for several reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your emails might be treated as spam, especially if you send them from a Dynamic IP&lt;/li&gt;
&lt;li&gt;Each recipient’s mail server will need to be resolved manually.&lt;/li&gt;
&lt;li&gt;Compared to other methods, querying DNS manually consumes more CPU and networking, making the performance worse&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In order to implement it, you’ll need to install a 3rd party plugin. DnsPlugin.NET is our choice here. See the sample code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the top of the file
// requires installation of https://www.nuget.org/packages/DnsClient
using System.Net;
using System.Net.Mail;
using DnsClient;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "See you Monday?";
message.Body = "Elizabeth, I didn't hear back from you. Let me know if we're still scheduled for Monday.";
LookupClient lookup = new LookupClient();
IDnsQueryResponse response = lookup.Query("westminster.co.uk", QueryType.MX);
foreach(DnsClient.Protocol.MxRecord record in response.Answers) {
    Console.WriteLine(ObjectDumper.Dump(record.Exchange));
    SmtpClient client = new SmtpClient(record.Exchange, 25);
    try
    {
        client.Send(message);
        // if we reached this point, our email was sent and we can break the loop
        break;
    }
    catch(SmtpException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using API to send emails
&lt;/h2&gt;

&lt;p&gt;A much better approach to sending emails without SMTP is with API. It’s definitely the fastest one. It also provides an additional layer of security by utilizing API keys and allows you to use many 3rd party providers that give you tons of additional features such as analytics, &lt;a href="https://mailtrap.io/blog/email-authentication/"&gt;email authentication&lt;/a&gt;, and others.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://mailtrap.io/email-api/"&gt;Mailtrap Email Delivery&lt;/a&gt; is one such service, and you get exemplary APIs for nine programming languages. More importantly, we provide comprehensive stats and deliverability alerts to help maintain your domain authority.&lt;/p&gt;

&lt;h2&gt;
  
  
  Receiving emails in C#
&lt;/h2&gt;

&lt;p&gt;Finally, you might be wondering if there’s a way to receive the emails directly with the C# code. After all, the Queen might get back to us any minute now. Of course, you could easily track new emails with simple email clients, such as Gmail or Thunderbird, without a single line of code and with minimal effort. But let’s assume you need to see at least the topics of incoming emails with your code, for example, to build some integrations around that.&lt;/p&gt;

&lt;p&gt;Receiving emails is not a part of core C# stack so you will need to utilize some 3rd party libraries for that purpose. &lt;a href="https://sourceforge.net/projects/hpop/"&gt;OpenPop.NET open-source library&lt;/a&gt; seems to be getting the job done in this case. You can use the following code to fetch the topics of incoming mail:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var client = new POPClient();
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("piotr@mailtrap.io", "My_password_here");
var count = client.GetMessageCount();
Message message = client.GetMessage(count);
Console.WriteLine(message.Headers.Subject);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the details on using OpenPop library for this or any other purposes, please refer to &lt;a href="http://hpop.sourceforge.net/documentation/"&gt;their documentation&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Try it out when you launch your first project but consider some more robust solutions if you plan to scale. If you need to do some email testing, the last thing you want is users receiving the test emails they were not supposed to get.&lt;/p&gt;

&lt;p&gt;Testing out of the way, feel free to check out &lt;a href="https://mailtrap.io/email-api/"&gt;Mailtrap’s Email Delivery&lt;/a&gt; for free and ensure your &lt;a href="https://mailtrap.io/blog/transactional-emails/"&gt;transactional emails&lt;/a&gt; reach the right recipients.&lt;/p&gt;

&lt;p&gt;That's all! Thanks for reading our guide on &lt;a href="canonical_url:%20https://mailtrap.io/blog/send-emails-in-net/"&gt;how to send HTML email using ASP.NET&lt;/a&gt;, which was originally published in the Mailtrap Blog by Piotr Malek. &lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
  </channel>
</rss>
