<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by MailSlurp | Email APIs for developers on Medium]]></title>
        <description><![CDATA[Stories by MailSlurp | Email APIs for developers on Medium]]></description>
        <link>https://medium.com/@mailslurp?source=rss-fbbb220ffadf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*hGcPGDTOtpgRyNeRcZEnnw.png</url>
            <title>Stories by MailSlurp | Email APIs for developers on Medium</title>
            <link>https://medium.com/@mailslurp?source=rss-fbbb220ffadf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 09:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mailslurp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to set up DNS records for sending SMTP emails]]></title>
            <link>https://mailslurp.medium.com/how-to-set-up-dns-records-for-sending-smtp-emails-79237e016e34?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/79237e016e34</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[email-marketing-tips]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 01:12:57 GMT</pubDate>
            <atom:updated>2024-04-22T01:12:57.851Z</atom:updated>
            <content:encoded><![CDATA[<p>A domain name and DNS records are required to be configured to send an SMTP email. This guide explains how to configure DNS records for SMTP mail servers and for when using a Mailslurp custom domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86eQRZa0dP2igrjytWac4Q.jpeg" /></figure><h3>What is DNS?</h3><p>DNS (Domain Name System) is a hierarchical decentralized naming system that translates human-readable domain names into IP addresses that computers can understand. It is a critical component of the internet infrastructure that enables users to access websites, send and receive emails, and perform other online activities.</p><p>The DNS works by maintaining a distributed database of domain names and their associated IP addresses. When a user types a domain name into their web browser, the browser sends a request to a DNS resolver to look up the IP address for that domain name. The DNS resolver queries a series of DNS servers to find the authoritative name server for the domain, which returns the IP address for the domain name. The DNS resolver then caches the IP address for future use, reducing the need for subsequent DNS lookups.</p><p>In addition to translating domain names to IP addresses, the DNS system also supports other types of records, such as MX records for email servers, SRV records for service discovery, TXT records for arbitrary text data, and more. These records are stored in DNS zone files that are managed by domain name registrars or DNS hosting providers.</p><h3>Configuring your own MailServer</h3><p>Configuring DNS records for SMTP mailservers is an essential step in setting up your email service. DNS (Domain Name System) is responsible for translating domain names into IP addresses that computers can understand. In this guide, we’ll walk you through the process of configuring DNS records for SMTP mailservers.</p><h3>1. A record</h3><p>The first record you need to configure is an A record. An A record maps a domain name to an IP address. You will need to create an A record for your SMTP server, such as smtp.example.com, that points to the IP address of your mail server. This record helps other mail servers locate your SMTP server when they need to send email to your domain.</p><p><strong>Example</strong>:</p><pre>smtp.example.com A 192.168.1.1</pre><h3>2. MX record</h3><p>The next record you need to configure is an MX record. An MX record specifies the mail server responsible for accepting email messages for your domain. When a mail server receives an email message for your domain, it will use the MX record to determine where to deliver the message.</p><p><strong>Example</strong>:</p><pre>example.com MX 10 smtp.example.com</pre><p>In this example, we’re specifying that smtp.example.com is the mail server responsible for accepting email messages for example.com. The number “10” is the priority value, which indicates the order in which mail servers should be used. If you have multiple MX records, the lowest number is the highest priority.</p><h3>3. PTR record</h3><p>The PTR record is used to map an IP address to a domain name. This record is essential for spam filters to verify the authenticity of the email source. You will need to create a PTR record that maps your mail server’s IP address to the domain name of your SMTP server.</p><p><strong>Example</strong>:</p><pre>1.1.168.192.in-addr.arpa PTR smtp.example.com</pre><p>In this example, we’re specifying that the IP address 192.168.1.1 is associated with the domain name smtp.example.com.</p><h3>4. SPF record</h3><p>An SPF (Sender Policy Framework) record is used to prevent email spoofing. It is a DNS record that specifies which IP addresses are authorized to send email on behalf of your domain. You will need to create an SPF record that includes the IP addresses of your SMTP server and any other authorized mail servers.</p><p><strong>Example</strong>:</p><pre>example.com TXT &quot;v=spf1 a mx ip4:192.168.1.1 ~all&quot;</pre><p>In this example, we’re specifying that any IP address that resolves to the A or MX record for example.com is authorized to send email on behalf of the domain. We’re also including the IP address of our SMTP server, 192.168.1.1, and specifying that any other IP address should be treated as a soft fail (~all).</p><h3>5. DKIM record</h3><p>DKIM (DomainKeys Identified Mail) is an email authentication method that allows the receiver to check if an email message was actually sent and authorized by the owner of that domain. DKIM works by adding a digital signature to each outgoing message that can be verified by the recipient’s mail server. You will need to generate a DKIM key and create a DKIM record in your DNS zone file.</p><p><strong>Example</strong>:</p><pre>default._domainkey.example.com TXT &quot;v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDqNfTnOvSjm+e6wxJF6pKjOc4vWT4WU6+aeH6J2B6wvPl+LtJOlZ8XBgKs1xJ0F+T0azLzNHq3h16eJzC1ZnBbZvx/9</pre><h3>Setup MailSlurp custom domains</h3><p>Create a <a href="https://www.mailslurp.com/guides/email-address-custom-domain-setup-step-by-step/">custom domain</a> in the MailSlurp <a href="https://app.mailslurp.com/login/">dashboard</a> and obtain the necessary DNS records. Add the TXT, DKIM and MX records to your DNS provider. You can use the <a href="https://www.mailslurp.com/docs/">MailSlurp dashboard</a> to verify that the records are correct.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/guides/dns-records/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79237e016e34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending Emails in JavaScript (NodeJS) with Nodemailer Tutorial]]></title>
            <link>https://mailslurp.medium.com/sending-emails-in-javascript-nodejs-with-nodemailer-tutorial-8a5eeca13c88?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5eeca13c88</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 00:00:16 GMT</pubDate>
            <atom:updated>2024-04-16T05:50:51.052Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to send emails directly from the client-side with JavaScript and Node.js using step-by-step examples &amp; practical solutions.</em></p><p>JavaScript is a programming language that’s versatile, working for both front-end and back-end development. This article will guide you through using JavaScript on the client-side to send emails from an application without needing a back-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbodQldSSMMeXxBZYWGs6Q.jpeg" /></figure><h3>Using JavaScript for email transmission</h3><p>When it comes to sending emails, JavaScript has its limitations — it can’t directly send emails due to its lack of support for server sockets. However, JavaScript is often used in conjunction with server-side languages to facilitate communication with SMTP servers. Together, they seamlessly communicate with SMTP servers, enabling the server script to send emails from the browser in response to user queries.</p><h3>Why use JavaScript to send emails?</h3><p>Emails are typically sent from the server-side of a standard app, which requires a server setup using back-end technology. When a request is made from the client-side, the server receives it, creates an email, and sends it to the SMTP server.</p><p>Why then would you want to use JavaScript to send emails directly from the client side? Such a method is quite helpful for developing contact forms and other user interfaces for web apps since it enables email sending without requiring the user to reload the page they are currently viewing. Additionally, you don’t need to play around with server programming. If your web application solely sends emails in response to contact forms, this approach could also be appealing.</p><h3>How to use JavaScript for client-side email sending</h3><p>To enable client-side email sending in your app with JavaScript, you have several options:</p><h3>Mailto: for delivering form data</h3><p>You can program the browser to launch the default mail client to send an email directly through JS. Although it is not technically possible to send an email straight from a browser, the mailto: method can be used.</p><h4>HTML example</h4><p>See how the following piece of code functions:</p><pre>&lt;form action=&quot;you@yourdmainhere.com&quot; method=&quot;post&quot; enctype=&quot;text/plain&quot; &gt;<br>FirstName:&lt;input type=&quot;text&quot; name=&quot;FirstName&quot;&gt;<br>Email:&lt;input type=&quot;text&quot; name=&quot;Email&quot;&gt;<br>&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>&lt;/form&gt;</pre><p>You’ll see the following when you open it in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8CD29Dkn2wewAXsKGTtXg.jpeg" /></figure><p>Following the data submission, the browser launches the default mail client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWLDqwFcNnD7r6MB81vmDw.jpeg" /></figure><p>Although the mailto: method is a fairly simple implementation, it has the following specific drawbacks:</p><ul><li>Given that the data is supplied in the form that the browser sends, you do not influence how the data is laid out.</li><li>Mailto: doesn’t guard against spambots gathering your email address. A link might be built-in JS in the past to help with this. Nowadays, a growing number of bots use JS and do not solely rely on HTML produced by the server.</li></ul><h3>SmtpJS with a SMTP Server</h3><p>A free package called SmtpJS can be used to send emails from JavaScript. To complete the task, an SMTP server and a few adjustments are required. Since <a href="https://www.mailslurp.com/api/">MailSlurp</a> is a practical email testing solution, it serves as the server in this example. The procedure to follow is outlined below: Create an HTML file with the following script in it (for instance, test.html):</p><pre>&lt;script src=&quot;https://smtpjs.com/v3/smtp.js&quot;&gt;<br>&lt;/script&gt;</pre><p>A button that will activate the JavaScript function should be created.</p><pre>&lt;input type=&quot;button&quot; value=&quot;Send Email&quot; onclick=&quot;sendEmail()&quot;&gt;</pre><p>Create the JS function to use SmtpJS.com to send emails.</p><pre>function sendEmail() {<br>Email.send({<br>    Host : &quot;smtp.mailslurp.com&quot;,<br>    Username : &quot;&lt;mailslurp username&gt;&quot;,<br>    Password : &quot;&lt;mailslurp password&gt;&quot;,<br>    To : &#39;recipient@example.com&#39;,<br>    From : &quot;sender@example.com&quot;,<br>    Subject : &quot;Test email&quot;,<br>    Body : &quot;&lt;html&gt;&lt;h2&gt;Header&lt;/h2&gt;&lt;strong&gt;Bold text&lt;/strong&gt;&lt;br/&gt;&lt;/br&gt;&lt;em&gt;Italic&lt;/em&gt;&lt;/html&gt;&quot;<br>}).then(message =&gt; alert(message)<br>);<br>}</pre><p>You can include an array of email addresses in the To: attribute if you have numerous recipients. Send emails by running “test.html” in the browser.</p><p>The problem with the code example above is that the client-side script makes your login and password visible. If you use the SmtpJS encryption option, you can resolve this. After completing the necessary fields, click the box that says “Encrypt your SMTP credentials.” Following that, select Generate security token, and use it in your JS function in place of the following SMTP server settings:</p><pre>SecureToken : &quot;&lt;your generated token&gt;&quot;</pre><p>An HTML email sample and an email with an attachment are shown below. This is how the email will appear in the recipient’s inbox, thanks to mailslurp’s GUI.</p><p>An example of HTML email coding:</p><pre>&lt;script src=&quot;https://smtpjs.com/v3/smtp.js&quot;&gt;&lt;/script&gt;<br>&lt;input type=&quot;button&quot; value=&quot;Send Email&quot; onclick=&quot;sendEmail()&quot;&gt;<br>&lt;script&gt;<br>function sendEmail() {<br> Email.send({<br>    SecureToken : &quot;&lt;your generated token&gt;&quot;,<br>    To : &#39;recipient@example.com&#39;,<br>    From : &quot;sender@example.com&quot;,<br>    Subject : &quot;Test Email&quot;,<br>    Body : &quot;&lt;html&gt;&lt;h2&gt;Header&lt;/h2&gt;&lt;strong&gt;Bold text&lt;/strong&gt;&lt;br/&gt;&lt;/br&gt;&lt;em&gt;Italic&lt;/em&gt;&lt;/html&gt;&quot;<br>    }).then(<br>        message =&gt; alert(&quot;mail sent successfully&quot;)<br>    );<br>}<br>&lt;/script&gt;</pre><p>Sample of the code needed to send an email with attachments Use the Attachments property to send an email with an attachment as shown:</p><pre>&lt;script src=&quot;https://smtpjs.com/v3/smtp.js&quot;&gt;&lt;/script&gt;<br>&lt;input type=&quot;button&quot; value=&quot;Send Email&quot; onclick=&quot;sendEmail()&quot;&gt;<br>&lt;script&gt;<br>function sendEmail() {<br>Email.send({<br>    SecureToken : &quot;&lt;your generated token&gt;&quot;,<br>    To : &#39;recipient@example.com&#39;,<br>    From : &quot;sender@example.com&quot;,<br>    Subject : &quot;Test Email&quot;,<br>    Body : &quot;&lt;html&gt;&lt;h2&gt;Header&lt;/h2&gt;&lt;strong&gt;Bold text&lt;/strong&gt;&lt;br/&gt;&lt;/br&gt;&lt;em&gt;Italic&lt;/em&gt;&lt;/html&gt;&quot;,<br> Attachments : [<br> {<br>  name : &quot;smtp.png&quot;,<br>  path : &quot;https://…/smtp.png&quot;<br> }]<br> }).then(message =&gt; alert(message)<br> );<br>}<br>&lt;/script&gt;</pre><h3>Sending emails without code</h3><p>MailSlurp.com offers a hassle-free way to connect email providers, create email templates, and send emails directly from JavaScript, all without the need for server-side code. Whether you prefer to use personal services like Gmail or Outlook, or well-known transactional services like Amazon SES or Mailgun, MailSlurp has you covered.</p><p>Using MailSlurp’s built-in editor, you can easily create email templates and customize them to suit your needs. The editor offers a range of tools, including auto-reply and reCAPTCHA verification, making email creation a breeze. Once you’ve crafted your email, simply click “Save” to store it for future use.</p><p>One of MailSlurp.com’s standout features is its ability to conceal standard email characteristics, ensuring your emails look professional and legitimate. Since the recipient field is included in the template and cannot be changed using JS, you transmit the template that was previously set up. To get started, install the MailSlurp SDK using npm.</p><pre>npm install mailslurp-com --save</pre><p>Via browser</p><pre>bower install mailslurp-com --save</pre><p>You should insert the following code before the closing tag if you need to use mailslurp on your website:</p><pre>&lt;script type=&quot;text/javascript&quot;<br>        src=&quot;https://cdn.jsdelivr.net/npm/mailslurp-com@2.4.0/dist/email.min.js&quot;&gt;<br>&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>   (function(){<br>      mailslurp.init(&quot;YOUR_USER_ID&quot;); //use your USER ID<br>   })();<br>&lt;/script&gt;</pre><p>Two techniques can be used to send the email itself:</p><ul><li>mailslurp.send</li><li>mailslurp.sendForm</li></ul><h4>mailslurp.send</h4><pre>var templateParams = {<br>    name: &#39;James&#39;,<br>    notes: &#39;Check this out!&#39;<br>};<br><br>mailslurp.send(&#39;YOUR_SERVICE_ID&#39;, &#39;YOUR_TEMPLATE_ID&#39;, templateParams) //use your Service ID and Template ID<br>    .then(function(response) {<br>       console.log(&#39;SUCCESS!&#39;, response.status, response.text);<br>    }, function(error) {<br>       console.log(&#39;FAILED...&#39;, error);<br>    });</pre><h4>mailslurp.sendForm</h4><pre>var templateParams = {<br>    name: &#39;James&#39;,<br>    notes: &#39;Check this out!&#39;<br>};<br><br>mailslurp.sendForm(&#39;YOUR_SERVICE_ID&#39;, &#39;YOUR_TEMPLATE_ID&#39;, templateParams) //use your Service ID and Template ID<br>    .then(function(response) {<br>       console.log(&#39;SUCCESS!&#39;, response.status, response.text);<br>    }, function(error) {<br>       console.log(&#39;FAILED...&#39;, error);<br>    });</pre><p>Let’s send an email directly from the browser to see if mailslurp.com functions as expected. We have created a straightforward template and set up the mailslurp email service. Now, we must write the following code into an HTML file:</p><pre>&lt;script type=&quot;text/javascript&quot;<br>        src=&quot;https://cdn.jsdelivr.net/npm/mailslurp-com@2.4.0/dist/email.min.js&quot;&gt;<br>&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>   (function(){<br>      mailslurp.init(&quot;&lt;USER-ID&gt;&quot;); //Insert your User ID<br>   })();<br>&lt;/script&gt;<br>&lt;script&gt;<br> var templateParams = {<br>    name: &#39;Sender&#39;,<br>    notes: &#39;Test email&#39;<br>};<br><br>mailslurp.send(&#39;&lt;email-service-ID&gt;&#39;, &#39;&lt;email-template-ID&gt;&#39;, templateParams) //Insert your email service ID and email template ID<br>    .then(function(response) {<br>       console.log(&#39;SUCCESS!&#39;, response.status, response.text);<br>    }, function(error) {<br>       console.log(&#39;FAILED...&#39;, error);<br>    });<br>&lt;/script&gt;<br></pre><p>Try it out in your browser by opening the MailSlurp Demo Inbox. It works!</p><p>However, there is a way to send emails without ever using a browser that is simpler and faster. After testing them, MailSlurp Email Delivery enables you to rapidly authenticate your domain and send emails using SMTP or API.</p><h3>To conclude</h3><p>In this tutorial, we have explored how JavaScript, in conjunction with Node.js, can be used to send emails directly from the client-side. By leveraging JavaScript’s capabilities, developers can create dynamic and interactive email features within their web applications. Whether it’s using the mailto: method for simple form data delivery or utilizing packages like SmtpJS for more advanced email sending, JavaScript offers a range of options for client-side email transmission.</p><p>Additionally, services like MailSlurp provide convenient solutions for sending emails without the need for complex server-side code. With its built-in editor and seamless integration with JavaScript, MailSlurp makes it easy to connect email providers, create templates, and send emails directly from your application.</p><p>Overall, JavaScript’s versatility makes it a valuable tool for email transmission, offering developers a range of options to suit their specific needs. Whether you’re looking to enhance user interactions or streamline your email sending process, JavaScript has you covered.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/blog/javascript-send-email/"><em>https://www.mailslurp.com</em></a><em> on March 1, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5eeca13c88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP’s mail() Function — the ultimate guide to email in PHP (and how to connect over SMTP)]]></title>
            <link>https://mailslurp.medium.com/phps-mail-function-the-ultimate-guide-to-email-in-php-and-how-to-connect-over-smtp-8247a9ba8c7d?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8247a9ba8c7d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[email-marketing]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 23:00:14 GMT</pubDate>
            <atom:updated>2024-02-21T23:10:46.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>PHP mail() Function — the ultimate guide to email in PHP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkxx_5SRF4El54yGZ_1X5g.jpeg" /><figcaption>Sending email is easy, using the surprisingly <em>powerful mail() function and a built-in SMTP relay.</em></figcaption></figure><p>Email functionality is a critical component for a vast array of web applications, from simple contact forms to complex notification systems. PHP, being a server-side scripting language, offers a built-in function for sending emails — the mail() function.</p><p>This guide dives deep into the nuances of using mail(), covering everything from basic usage to more advanced scenarios involving attachments and different content types. We’ll also explore the setup requirements across different operating systems, the necessity of a remote mail server, and alternatives for reading and testing email functionalities in PHP.</p><h3>Understanding the mail() Function in PHP</h3><p>The mail() function in PHP is a straightforward yet powerful tool for sending emails directly from a script. It constructs and sends a standard email, including headers and message body, using the local mail server or a specified SMTP server.</p><h3>Basic Usage of mail()</h3><p>Sending an email with the function involves specifying the recipient’s email address, subject, message body, and additional headers as needed. Here’s a simple example:</p><pre>&lt;?php<br>$to = &#39;recipient@example.com&#39;;<br>$subject = &#39;Test Mail&#39;;<br>$message = &#39;Hello, this is a test email.&#39;;<br>$headers = &#39;From: webmaster@example.com&#39;;<br><br>if(mail($to, $subject, $message, $headers)) {<br>    echo &quot;Email sent successfully!&quot;;<br>} else {<br>    echo &quot;Email sending failed.&quot;;<br>}</pre><p>This snippet sends a basic email to recipient@example.com with a simple message. The From header is used to specify the sender&#39;s email address.</p><h3>A More Complex Example: Attachments and Multiple Content Types</h3><p>Sending emails with attachments or mixed content types (e.g., combining text and HTML) requires constructing a multipart email. This involves specifying boundaries in the email body to separate different parts of the message, including the attachment data encoded in base64.</p><pre>&lt;?php<br>$to = &#39;recipient@example.com&#39;;<br>$subject = &#39;Test Mail with Attachment&#39;;<br>$from = &#39;webmaster@example.com&#39;;<br><br>// To send HTML mail, the Content-type header must be set<br>$headers = &quot;From: $from\r\n&quot;;<br>$headers .= &quot;MIME-Version: 1.0\r\n&quot;;<br>$headers .= &quot;Content-Type: multipart/mixed; boundary=\&quot;boundary1\&quot;\r\n\r\n&quot;;<br><br>// Message body<br>$body = &quot;--boundary1\r\n&quot;;<br>$body .= &quot;Content-Type: text/plain; charset=ISO-8859-1\r\n&quot;;<br>$body .= &quot;Content-Transfer-Encoding: 7bit\r\n\r\n&quot;;<br>$body .= &quot;This is a MIME encoded message.\r\n\r\n&quot;;<br><br>// Attachment<br>$file = &quot;path/to/attachment.zip&quot;;<br>$attachment = chunk_split(base64_encode(file_get_contents($file)));<br>$body .= &quot;--boundary1\r\n&quot;;<br>$body .= &quot;Content-Type: application/zip; name=\&quot;attachment.zip\&quot;\r\n&quot;;<br>$body .= &quot;Content-Transfer-Encoding: base64\r\n&quot;;<br>$body .= &quot;Content-Disposition: attachment; filename=\&quot;attachment.zip\&quot;\r\n\r\n&quot;;<br>$body .= $attachment . &quot;\r\n&quot;;<br>$body .= &quot;--boundary1--&quot;;<br><br>// Sending email<br>if(mail($to, $subject, $body, $headers)) {<br>    echo &quot;Email sent successfully with attachment!&quot;;<br>} else {<br>    echo &quot;Email sending failed.&quot;;<br>}</pre><p>This example demonstrates sending an email with both text and an attachment, using MIME encoding and specifying content types and boundaries.</p><h3>Setup Requirements for Using mail()</h3><p>The mail() function&#39;s behavior and capabilities depend significantly on the server configuration, particularly the settings in the php.ini file and the underlying mail server setup (Sendmail on Unix/Linux or SMTP on Windows).</p><h3>Configuring php.ini and Mail Server</h3><ul><li><strong>On Linux/Unix (Sendmail)</strong>: The sendmail_path directive in php.ini should point to the Sendmail executable. This is typically configured correctly by default on most Linux distributions.</li><li><strong>On Windows (SMTP)</strong>: Windows servers require specifying the SMTP server and port in php.ini:</li></ul><pre>[mail function]<br>SMTP = smtp.example.com<br>smtp_port = 25<br>sendmail_from = user@example.com</pre><ul><li><strong>On macOS</strong>: Similar to Linux, macOS uses Sendmail or Postfix. Ensure the sendmail_path is correctly set in php.ini.</li></ul><p>After adjusting php.ini, restart your web server for the changes to take effect.</p><p>Integrating the new sections into the previously outlined blog post, we enrich the guide with deeper insights into configuring email sending environments, specifically focusing on Sendmail and the Windows platform. These additions aim to provide a comprehensive understanding of the underlying systems that support PHP’s mail() function.</p><h3>How email is sent by PHP</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-gVB7WvHvfw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-gVB7WvHvfw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-gVB7WvHvfw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d65bb13b4e904017168c542a9cb5f5a0/href">https://medium.com/media/d65bb13b4e904017168c542a9cb5f5a0/href</a></iframe><p>Depending on your platform, PHP will call either sendmail or, on Windows, use the built in SMTP system calls.</p><p>Sendmail is one of the oldest and most widely used mail transfer agents (MTA) on Unix-like operating systems. It’s responsible for the routing and delivery of email. The PHP mail() function can utilize Sendmail (or compatible MTAs like Postfix) for sending emails from scripts. On systems where Sendmail is not pre-installed or configured, manual setup is required to enable email sending capabilities.</p><h3>Why Install Sendmail?</h3><ul><li><strong>Direct Mail Sending</strong>: Sendmail allows PHP applications to send emails directly from the server without relying on external SMTP services.</li><li><strong>Flexibility</strong>: It offers extensive configuration options for handling mail, including routing, authentication, and security measures.</li><li><strong>Compatibility</strong>: Sendmail’s widespread support makes it a reliable choice for a variety of applications and server environments.</li></ul><h3>Setting Up and Using Sendmail</h3><h4>Installation on Linux</h4><p>Most Linux distributions include Sendmail or an alternative like Postfix. To install Sendmail, you can use the package manager:</p><pre># For Debian/Ubuntu<br>sudo apt-get update<br>sudo apt-get install sendmail<br><br># For CentOS/RHEL<br>sudo yum update<br>sudo yum install sendmail</pre><h4>Basic Configuration</h4><p>After installation, a basic configuration step is to ensure Sendmail is running and that PHP is configured to use it:</p><ol><li><strong>Start Sendmail</strong>:</li></ol><pre>sudo systemctl start sendmail</pre><p><strong>2. Ensure PHP is Configured to Use Sendmail</strong>: This usually involves verifying the sendmail_path directive in php.ini points to the Sendmail executable. A typical setting might look like:</p><pre>sendmail_path = &quot;/usr/sbin/sendmail -t -i&quot;</pre><p><strong>3. Test Sendmail</strong>: You can test Sendmail’s functionality directly from the terminal:</p><pre>echo &quot;Subject: Test Mail&quot; | sendmail -v recipient@example.com</pre><p>This command sends a simple email to recipient@example.com, with verbose output to help diagnose any issues.</p><h3>How Windows Sends Emails</h3><p>Windows systems do not include Sendmail or a native equivalent. Instead, PHP on Windows uses SMTP to send emails. The configuration for this is done within the php.ini file, where you specify the SMTP server details that PHP should use:</p><pre>[mail function]<br>; Setup for SMTP sending<br>SMTP = smtp.example.com<br>smtp_port = 587<br>sendmail_from = user@example.com</pre><p>For sending emails through SMTP on Windows, you need access to an SMTP server. This could be a service provided by your hosting company, an external email service like Gmail, or a local SMTP server running on your network. After configuring php.ini, restart your web server for the changes to take effect.</p><h4>Additional SMTP Configuration for Windows</h4><p>When using an external SMTP server, especially one that requires authentication, consider using a library like PHPMailer or SwiftMailer. These libraries offer a more straightforward approach to handling SMTP details, including authentication and encryption, which are not directly supported by PHP’s mail() function on Windows.</p><h3>Why You Need a Remote Mail Server (SMTP) to Send Emails</h3><p>While the mail() function can send emails using a local mail server, using a remote SMTP server is often necessary for reliability, scalability, and security. A remote SMTP server handles email delivery, including queueing, retries, and bounce handling, more efficiently than a local setup, especially for applications with significant email traffic.</p><blockquote>If you need a new SMTP server fast, try <a href="https://www.mailslurp.com/">MailSlurp’s </a>free developer mail server APIs. <a href="https://app.mailslurp.com/">Sign up today</a></blockquote><h3>Reading Emails: IMAP and POP3 in PHP</h3><p>PHP can interact with email servers not just to send but also to read emails using the IMAP and POP3 protocols. The imap_open function allows PHP scripts to connect to mail servers for reading messages, searching mailboxes, and managing emails programmatically. This capability is essential for applications that need to process incoming emails, such as support ticket systems.</p><h3>Mocking and Testing mail() Usage in PHPUnit</h3><p>Testing code that sends emails with mail() can be challenging. To avoid sending actual emails during tests, you can mock the mail() function using PHPUnit&#39;s mocking capabilities. This involves creating a mock object that simulates the behavior of mail() without executing its real functionality, allowing you to verify that your code attempts to send an email under the right conditions.</p><h3>Limitations of mail() and Alternatives</h3><p>While mail() is suitable for simple email sending tasks, its limitations become apparent with more complex requirements, such as SMTP authentication, encryption, and detailed error handling. Libraries like PHPMailer and SwiftMailer offer a more robust solution, providing comprehensive email sending features with support for SMTP, HTML emails, attachments, and more.</p><h3>Conclusion</h3><p>The PHP mail() function serves as a basic tool for sending emails, but its simplicity comes with limitations. For production environments and applications with complex email sending needs, leveraging a dedicated library like PHPMailer or integrating with a professional SMTP service provides greater flexibility, reliability, and security. Regardless of the method chosen, understanding the underlying configuration and testing practices ensures that your application&#39;s email functionality meets its requirements effectively.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/blog/php-mail-function/"><em>https://www.mailslurp.com</em></a><em> on October 10, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8247a9ba8c7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Email for Testing (Test Email Accounts)]]></title>
            <link>https://mailslurp.medium.com/using-email-for-testing-test-email-accounts-5540b8e35c2a?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5540b8e35c2a</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 00:00:28 GMT</pubDate>
            <atom:updated>2024-03-14T02:55:36.213Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Explore the benefits of using dummy email accounts for testing PLUS the best random email generators to create them quickly</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RjhNfP8-w1GkuX0f.jpg" /></figure><p>If you are a QA tester or software developer, you will come across the need to have lots and lots of testing email accounts. These are disposable or throwaway email addresses you can use to test the sending and receiving of messages in your application.</p><h3>Why is it important to have dummy email addresses?</h3><p>There are many reasons to use test email addresses. These include the need to use <a href="https://www.mailslurp.com/guides/test-user-sign-up-with-test-email-accounts/">test email accounts</a> to simulate the mass emails that you are going to send out through an application. Additionally, blank mail addresses can be used to test application login and authentication processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4-z_VU9wE0f8Fax9LT6Cg.jpeg" /></figure><p>Without test email accounts, it’s not possible to detect issues before you deploy the system in production. Instead of creating dummy email addresses manually, you should think about using a random email generator. It will help you to get all the dummy email addresses that you want for <a href="https://www.mailslurp.com/blog/how-to-test-an-email-address/">testing</a> purposes within a short period of time.</p><h3>How do dummy emails work?</h3><p>Dummy emails are temporary email addresses, which you can get for a short period of time. There are service providers who offer dummy emails. However, you can proceed with creating them on your own as well.</p><p>You will be getting a unique email address, which you can use to receive emails. However, some of the dummy emails will even provide you the opportunity to send out emails. In most instances, dummy emails would have a validity of around 10 minutes to few hours.</p><h3>Where can you create dummy emails?</h3><p>If you want to create dummy emails quickly, you should locate the best random email generator out there. Here are few such options available to consider.</p><h4>MailSlurp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M33PLY_98up4ZnDM5cfXUQ.jpeg" /></figure><p>MailSlurp is the leading email address generator. Create unlimited test email accounts and use the powerful <a href="https://docs.mailslurp.com/">email API</a> and dashboard to control inboxes and <a href="https://www.mailslurp.com/guides/custom-domains/">custom domains</a>.</p><h3>Creating disposable mail accounts</h3><p>You can send and receive email in code from disposable email addresses:</p><pre>// create a randomly assigned email address<br>const mailslurp = new MailSlurp({ apiKey });<br>const { id, emailAddress } = await mailslurp.createInbox();</pre><p>Create a <a href="https://app.mailslurp.com/">free account</a> and generate infinite throwaway of permanent test email accounts that can be controlled with SMTP, <a href="https://docs.mailslurp.com/">REST API</a>, or <a href="https://www.mailslurp.com/guides/dashboard/">dashboard</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*39WTS_ZUqjepMx9A_leqTw.jpeg" /><figcaption><em>Use the online email client or create and control emails in Java, NodeJS, PHP, CSharp, Python and more.</em></figcaption></figure><h3>Reading temporary mail in code and tests</h3><p>With MailSlurp’s SDK libraries you can easily wait for expected email content during tests and extract content.</p><pre>// send an email containing a link to the inbox<br>await mailslurp.sendEmail(inboxId!, {<br>  to: [emailAddress!],<br>  subject: &#39;Please click the link provided&#39;,<br>  body: &#39;&lt;p&gt;https://my.app/confirm&lt;/p&gt;&#39;,<br>});<br>// wait for matching email to arrive with desired subject<br>const waitForController = new WaitForControllerApi(<br>  new Configuration({ apiKey })<br>);<br>const confirmation = await waitForController.waitForMatchingFirstEmail({<br>  inboxId,<br>  unreadOnly: true,<br>  timeout: 30000,<br>  matchOptions: {<br>    matches: [<br>      {<br>        field: MatchOptionFieldEnum.SUBJECT,<br>        should: MatchOptionShouldEnum.CONTAIN,<br>        value: &#39;Please click the link provided&#39;,<br>      },<br>    ],<br>  },<br>});<br>// extract the link using regex pattern on the confirmation body<br>const results = /&lt;p&gt;(https.+)&lt;\/p&gt;/g.exec(confirmation.body!)!;<br>expect(results.length).toBe(2);<br>const url = decodeURIComponent(results[1]);<br>expect(url).toContain(&#39;https://my.app/confirm&#39;);</pre><h3>Sending email from test accounts</h3><p>You can also <a href="https://www.mailslurp.com/blog/javascript-send-email/">send email</a> from test accounts. This is useful for testing email sending and notifications. You can easily send emails using the MailSlurp <a href="https://docs.mailslurp.com/">developer SDKs</a>:</p><pre>await mailslurp.sendEmail(inbox.id, {<br>  to: [recipientEmail],<br>  // can include names in addresses in the format below<br>  replyTo: &#39;&quot;Support&quot; &lt;support@my-ap.com&gt;&#39;,<br>  // quote the property if a reserved word<br>  [&#39;from&#39;]: inbox2.emailAddress,<br>});</pre><p>If you prefer to use SMTP clients you can use the MailSlurp SMTP server to send emails from any email client or library. Here is an example of how to configure the nodemailer client:</p><pre>// create an inbox using MailSlurp client<br>const mailslurp = new MailSlurp({ apiKey: process.env.API_KEY! });<br>const inbox = await mailslurp.createInboxWithOptions({<br>  inboxType: CreateInboxDtoInboxTypeEnum.SMTP_INBOX,<br>});<br>// get smtp access details for mailbox<br>const server = await mailslurp.inboxController.getImapSmtpAccess({<br>  inboxId: inbox.id,<br>});<br>// Create auth plain transport<br>const transport = nodemailer.createTransport({<br>  host: server.smtpServerHost,<br>  port: server.smtpServerPort,<br>  secure: false,<br>  auth: {<br>    user: server.smtpUsername,<br>    pass: server.smtpPassword,<br>    type: &#39;PLAIN&#39;,<br>  },<br>});<br>// Send email<br>const sent = await transport.sendMail({<br>  from: inbox.emailAddress,<br>  to: inbox.emailAddress,<br>  subject: &#39;Test outbound email&#39;,<br>  text: &#39;Can I send on behalf?&#39;,<br>  html: &#39;&lt;b&gt;Hello world&lt;/b&gt;&#39;,<br>});</pre><h3>Other services</h3><h4>Mailinator</h4><p>Mailinator is one of the most popular random email address generators you can find. You can get random and dummy email addresses for workflow testing with this. All the emails that you get will be having the @mailinator.com test domain. You will not be able to attach any files to the emails that you receive with Mailinator.</p><h4>Guerilla Mail</h4><p>Guerrilla Mail is a free service available for people who are looking for a random email generator. You don’t have to go through a sing up process to start using this service. It will provide you the chance to send emails and receive emails. However, it doesn’t have the best user interface for you to get work done.</p><h4>Maildrop</h4><p>Maildrop is an open-source project, which you can use to generate email addresses instantly. It is coming to you with a good-looking UI as well. It is an effective service that you can use to send out emails without attachments.</p><h4>Tempmail</h4><p>You may also use Tempmail to generate <a href="https://www.mailslurp.com/as/temp-mail-api/">disposable emails</a>. The inbox would show you all the incoming emails instantly, and you don’t have to refresh the page. This is available for free as well.</p><h4>Creating a fake email with your Gmail</h4><p>You may also use your Gmail to create a fake email for testing purposes. You should be using a Gmail account that you are not using. You just need to add a “+” to the preferred username and follow that with some random characters. For example, if your email address is &lt;johnsmith@gmail.com&gt;, you will be able to create the new email as &lt;johnsmith+testing@gmail.com&gt;.</p><p>Likewise, you will be provided with endless opportunities to add any random characters and create new email addresses. Gmail will treat each email address as a unique email account. You can set up filters within your Gmail inbox to segregate the incoming emails, respectively.</p><h3>Should you use temporary emails?</h3><p>Even though the idea of using temporary emails for testing purposes looks appealing, there are some limitations to it as well. For example, you cannot use it for complex applications, such as for situations where the recipients have different permission levels.</p><p>You will not also be able to use them to effectively test on mobile and web applications as well. In all such instances, you are encouraged to use <a href="https://www.mailslurp.com/about/how-it-works/">MailSlurp</a> — a powerful <a href="https://www.mailslurp.com/guides/test-email-address/">test email account</a> service.</p><h3>Testing with MailSlurp disposable email accounts</h3><p>MailSlurp is a free email platform for generating disposable (or permanent) mailboxes for testing and development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*DJfvas-zVG95IEMB5ATbKg.jpeg" /></figure><p>You can create and control inboxes in code, tests, or using the <a href="https://app.mailslurp.com/">online dashboard</a>. Here is an example using Javascript:</p><pre>const MailSlurp = require(&#39;mailslurp-client&#39;).default;<br>const mailslurp = new MailSlurp({<br>  apiKey: process.env.API_KEY ?? &#39;your-api-key&#39;,<br>});<br><br>// create an inbox with options using the inbox controller<br>const inbox = await mailslurp.inboxController.createInbox({<br>  // name is used a contact name when sending<br>  name: &#39;John Doe&#39;,<br>  // use the expanded domain pool so randomly assigned email address is more varied<br>  useDomainPool: true,<br>  // permanent by default or supply an expires at time<br>  expiresAt: undefined,<br>});</pre><h3>Automated end-to-end email testing</h3><p>MailSlurp enables application <a href="https://www.mailslurp.com/guides/email-testing/">integration testing</a> e2e using disposable email accounts.</p><h4>Use Cypress JS to test with email</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lx9I23ZcOWgRAyjWuTZe8g.jpeg" /><figcaption><em>Send and receive emails in Cypress JS to test application sign-up, verification and notifications.</em></figcaption></figure><p>See the <a href="https://www.mailslurp.com/guides/testing-email-with-cypress/">cypress test example</a> for more information.</p><h3>Playwright email testing</h3><p>Playwright is an awesome browser testing tool from Microsoft that offers a different approach to Cypress (or <a href="https://www.mailslurp.com/blog/capture-website-screenshots-nodejs/">Puppeteer</a>). With Playwright you can automate the integration testing of email processes with MailSlurp. Here is an example:</p><pre>import { test, expect, Page } from &#39;@playwright/test&#39;;<br>import MailSlurp from &quot;mailslurp-client&quot;;<br><br>test.describe(&#39;test email login with playwright&#39;, () =&gt; {<br>  test(&#39;can login and verify email address with mailslurp&#39;, async ({ page }) =&gt; {<br>    const apiKey = process.env.API_KEY;<br>    expect(apiKey).toBeDefined();<br><br>    // load playground app<br>    await page.goto(&quot;https://playground.mailslurp.com&quot;);<br>    await page.click(&#39;[data-test=&quot;sign-in-create-account-link&quot;]&#39;);<br><br>    // create a new inbox<br>    const mailslurp = new MailSlurp({ apiKey })<br>    const password = &quot;test-password&quot;<br>    const { id, emailAddress } = await mailslurp.createInbox()<br><br>    // fill sign up form<br>    await page.fill(&#39;input[name=email]&#39;, emailAddress);<br>    await page.fill(&#39;input[name=password]&#39;, password);<br>    await page.click(&#39;[data-test=&quot;sign-up-create-account-button&quot;]&#39;);<br><br>    // wait for verification code<br>    const email = await mailslurp.waitForLatestEmail(id)<br><br>    // extract the confirmation code (so we can confirm the user)<br>    const code = /([0-9]{6})$/.exec(email.body)[1];<br><br>    // enter confirmation code<br>    await page.fill(&#39;[data-test=&quot;confirm-sign-up-confirmation-code-input&quot;]&#39;, code);<br>    await page.click(&#39;[data-test=&quot;confirm-sign-up-confirm-button&quot;]&#39;);<br><br>    // fill out username (email) and password<br>    await page.fill(&#39;[data-test=&quot;username-input&quot;]&#39;, emailAddress);<br>    await page.fill(&#39;[data-test=&quot;sign-in-password-input&quot;]&#39;, password);<br>    // submit<br>    await page.click(&#39;[data-test=&quot;sign-in-sign-in-button&quot;]&#39;);<br>    await page.waitForSelector(&quot;[data-test=&#39;greetings-nav&#39;]&quot;)<br>  });<br><br>});</pre><p>See the <a href="https://www.mailslurp.com/examples/playwright-fake-email-test/">playwright guide</a> for examples.</p><h3>Selenium email testing</h3><p>Selenium is a popular browser automation tool. You can use it to test email processes with MailSlurp. Here is an example:</p><pre>/**<br> * Create a real email address with MailSlurp and use it to start sign-up on the playground<br> */<br>@Test<br>public void test3_canCreateEmailAddressAndSignUp() throws ApiException {<br>    // create a real, randomized email address with MailSlurp to represent a user<br>    InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);<br>    inbox = inboxControllerApi.createInbox(null,null,null,null,null,null,null, null, null);<br><br>    // check the inbox was created<br>    assertNotNull(inbox.getId());<br>    assertTrue(inbox.getEmailAddress().contains(&quot;@mailslurp.com&quot;));<br><br>    // fill the playground app&#39;s sign-up form with the MailSlurp<br>    // email address and a random password<br>    driver.findElement(By.name(&quot;email&quot;)).sendKeys(inbox.getEmailAddress());<br>    driver.findElement(By.name(&quot;password&quot;)).sendKeys(TEST_PASSWORD);<br><br>    // submit the form to trigger the playground&#39;s email confirmation process<br>    // we will need to receive the confirmation email and extract a code<br>    driver.findElement(By.cssSelector(&quot;[data-test=sign-up-create-account-button]&quot;)).click();<br>}</pre><h3>More options</h3><p>For more email testing options see these <a href="https://www.mailslurp.com/guides/">guides</a> and <a href="https://docs.mailslurp.com/">developer docs</a>.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/guides/email-for-testing-test-email-accounts/"><em>https://www.mailslurp.com</em></a><em> on September 1, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5540b8e35c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing email sign-up with RobotFramework Selenium]]></title>
            <link>https://mailslurp.medium.com/testing-email-sign-up-with-robotframework-selenium-a363a5cf4f05?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a363a5cf4f05</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 00:00:05 GMT</pubDate>
            <atom:updated>2025-06-01T21:20:56.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NJf2591vHtP-kQhX.jpg" /></figure><p>The tutorial is about how to test user sign-up and account verification flows using Python, Robot framework and MailSlurp. MailSlurp is a free Python SDK <a href="https://pypi.org/project/mailslurp-client/">published on PYPI</a> that lets you create real email addresses on demand. You can use it with Robot Framework to test user sign-up and email verification in real applications. View the <a href="https://github.com/mailslurp/examples/tree/master/python3-robotframework">example code on GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Vkig-5BuslonSDxp" /></figure><h3>Introduction to Robotframework</h3><p>Robot is a hugely popular integration testing framework with support for Python and Java. You can use Robot to test apps, software, websites and more. This tutorial will show you how to test a website sign-up process using real email addresses with <a href="https://www.mailslurp.com/guides/dashboard/view-email-addresses/">MailSlurp</a> and Robot.</p><h3>What is Robot?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*3aQtXjjaFHAVfZmS" /></figure><p>Robot is a little different to most other Python test frameworks like PyTest: it is keyword-driven or acceptance-test driven. That means you write tests using keywords instead of Python code. It is a bit like <a href="https://www.mailslurp.com/examples/test-emails-with-cucumber/">Cucumber</a> from <a href="https://docs.mailslurp.com/ruby/">Ruby</a>. Test files are written in .robot files using a custom syntax. We recommend finding a plugin for your editor that supports the robot file type to make testing easier.</p><h3>What do tests look like?</h3><p>Tests in RobotFramework are keyword driven and resemble sentences.</p><p>An example might look like so:</p><pre>*** Test Cases ***<br>Sign Up With New Email Address<br>    ${inbox}    Create Email Address<br>    Open Browser To Home Page<br>    Go To SignUp Page</pre><blockquote><em>NOTE: in Robot whitespace matters! Separate keywords and arguments with a tab or several whitespaces so that Robot can tell where keywords begin and end.</em></blockquote><p>Every keyword or sentence we write inside a robot file needs to be defined by a plugin or by ourselves using a custom plugin. We will do this to integrate MailSlurp.</p><h3>Demonstration project</h3><p>For this tutorial we will test the sign-up process of a <a href="https://playground.mailslurp.com/">real application</a> hosted at playground.mailslurp.com. This is a demonstration React App that uses AWS Firebase for authentication. After entering an email address and password during sign-up the user receives a confirmation code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*Xl7XpQOtWkC2FgHz" /></figure><p>The confirmation code must be extracted from the email and entered into the confirmation form to proceed. Once confirmed a user can log in and see a welcome page with a picture of a friendly dog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Z4nel5i4M0iK6_hj" /></figure><h3>Project setup</h3><p>First, let’s setup a project using Python3.</p><p>mkdir robotframework-email-testing-python &amp;&amp; cd -</p><h3>Install dependencies</h3><p>MailSlurp and Robot can be <a href="https://pypi.org/project/mailslurp-client/">found on PyPI</a>. Create a requirements.txt file and include the following dependencies:</p><pre>robotframework &gt;= 4.0.0<br>robotframework-seleniumlibrary &gt;= 5.1.3<br>mailslurp-client &gt;= 11.5.10<br>webdrivermanager &gt;= 0.10.0</pre><p>Notice we have included robotframework, the robot selenium plugin, MailSlurp and the webdriver manager. Selenium is used for browser testing to open the MailSlurp playground and fill out the login forms. The webdrivermanager is used to download a webdriver to automate browser testing.</p><p>Install the dependencies like so:</p><p>pip3 install -r requirements.txt</p><h3>Download webdrivers</h3><p>Selenium needs a webdriver for firefox (or your browser of choice) to automate it. Let’s use webdrivermanager to download geckodriver like so:</p><p>python3 -m webdrivermanager firefox -d . -l SKIP</p><p>Then move the driver to the user PATH</p><p>sudo mv gecko/v*/gecko*/geckodriver /usr/bin/geckodriver</p><h3>Setup tests</h3><p>To setup a Robot test we need to create a few files.</p><pre>touch test.robot<br>touch resource.robot</pre><h3>Create a MailSlurp plugin file</h3><p>To create email addresses during testing we need to include a plugin file called MailSlurp.py in the root directory.</p><pre>touch MailSlurp.py</pre><p>Inside the file include the following (we will explain it later):</p><pre>import mailslurp_client<br>import re</pre><pre># define a library to use mailslurp functions in robot test<br>class MailSlurp(object):<br>    ROBOT_LIBRARY_VERSION = &#39;1.0.0&#39;<br>    ROBOT_LIBRARY_SCOPE = &#39;GLOBAL&#39;</pre><pre>    # configure the mailslurp client using your API KEY<br>    def __init__(self, api_key):<br>        self.configuration = mailslurp_client.Configuration()<br>        self.configuration.api_key[&#39;x-api-key&#39;] = api_key</pre><pre>    # function for creating an email address returns an inbox with an id and email_address<br>    def create_inbox(self):<br>        with mailslurp_client.ApiClient(self.configuration) as api_client:<br>            # create an inbox using the inbox controller<br>            api_instance = mailslurp_client.InboxControllerApi(api_client)<br>            inbox = api_instance.create_inbox()<br>            return inbox</pre><pre>    # wait for and return an email in an inbox<br>    def wait_for_latest_email(self, inbox_id):<br>        with mailslurp_client.ApiClient(self.configuration) as api_client:<br>            # create an inbox using the inbox controller<br>            api_instance = mailslurp_client.WaitForControllerApi(api_client)<br>            email = api_instance.wait_for_latest_email(inbox_id=inbox_id, timeout=60000, unread_only=True)<br>            return email</pre><pre>    # parse the confirmation code from an email body (adjust for your own use)<br>    def extract_email_content(self, email_body):<br>        regex = &#39;Your Demo verification code is ([0-9]{6})&#39;<br>        pattern = re.compile(regex)<br>        matches = pattern.match(email_body)<br>        content = matches.group(1)<br>        return content</pre><p>This is how you define a plugin in Robot so that you can create custom test keywords. Now we need to include it.</p><h3>Create a resource file and include MailSlurp</h3><p>For Robot tests we need to define our keywords. Typically that involves a resource.robot file.</p><p>Add one that contains the following code:</p><pre># set up the tests<br>*** Settings ***<br>Documentation     Define keywords and variables and import MailSlurp functions<br>Library           SeleniumLibrary<br>Library           ./MailSlurp.py    ${MAILSLURP_API_KEY}</pre><pre># define variables and default values<br>*** Variables ***<br>${MAILSLURP_API_KEY}    PUT_YOUR_KEY_HERE<br>${SERVER}               playground.mailslurp.com<br>${BROWSER}              Firefox<br>${DELAY}                0<br>${PLAYGROUND URL}       <a href="https://${server}/">https://${SERVER}/</a><br>${TEST_PASSWORD}        test-password</pre><p>Above we defined library settings for Selenium and our custom functions. We also defined variables for use throughout our tests. Take note of the server url: <a href="https://playground.mailslurp.com/">https://playground.mailslurp.com</a> hosts the functioning React web app that allows sign-up and user confirmation via email verification codes.</p><h3>Include your API KEY</h3><p>In the *** Settings *** section we included two libraries: the Selenium Plugin and our custom MailSlurp file.</p><p>This line Library ./MailSlurp.py ${MAILSLURP_API_KEY} instantiates the MailSlurp.py file we created and passed the MAILSLURP_API_KEY variable to the class constructor:</p><pre># configure the mailslurp client using your API KEY<br>    def __init__(self, api_key):<br>        self.configuration = mailslurp_client.Configuration()<br>        self.configuration.api_key[&#39;x-api-key&#39;] = api_key</pre><p>MailSlurp is free to use but you need to sign-up to <a href="https://app.mailslurp.com/sign-up/">create an API KEY</a>. When running your robot tests set the variable on the command line with the --variable flag.</p><pre>python3 -m robot --variable MAILSLURP_API_KEY:$(API_KEY) --outputdir results test.robot</pre><h3>Defining test methods</h3><p>In Robot you define keywords and then use them to describe acceptance tests. Use the resource.robot file to define the actions you want to test. For our demonstration app we can define these actions below:</p><pre># see https://robotframework.org/SeleniumLibrary/SeleniumLibrary.html for selenium keywords<br>*** Keywords ***<br>Create Email Address<br>    ${inbox}    Create Inbox<br>    [Return]    ${inbox}</pre><pre>Wait For Confirmation Code<br>    [Arguments]     ${inbox_id}<br>    ${email}    Wait For Latest Email   ${inbox_id}<br>    ${code}     Extract Email Content   ${email.body}<br>    [Return]    ${code}</pre><pre>Open Browser To Home Page<br>    Open Browser    ${PLAYGROUND URL}    ${BROWSER}<br>    Maximize Browser Window<br>    Set Selenium Speed    ${DELAY}<br>    Home Page Should Be Open</pre><pre>Home Page Should Be Open<br>    Title Should Be    React App</pre><pre>SignUp Page Should Be Open<br>    Wait Until Element Contains     //*[@data-test=&quot;sign-up-header-section&quot;]//span   Sign Up</pre><pre>Go To SignUp Page<br>    Go To    ${PLAYGROUND URL}<br>    Home Page Should Be Open<br>    Click Element   //a[@data-test=&quot;sign-in-create-account-link&quot;]<br>    SignUp Page Should Be Open</pre><pre>Input Email<br>    [Arguments]    ${username}<br>    Input Text     //*[@name=&quot;email&quot;]    ${username}</pre><pre>Input Username<br>    [Arguments]    ${username}<br>    Input Text     //*[@name=&quot;username&quot;]    ${username}</pre><pre>Input Password<br>    [Arguments]    ${password}<br>    Input Text    //*[@name=&quot;password&quot;]    ${password}</pre><pre>Input Confirmation<br>    [Arguments]    ${code}<br>    Input Text    //*[@name=&quot;code&quot;]    ${code}</pre><pre>Submit Confirmation<br>    Click Button    //button[@data-test=&quot;confirm-sign-up-confirm-button&quot;]</pre><pre>Submit Credentials<br>    Click Button    //button[@data-test=&quot;sign-up-create-account-button&quot;]</pre><pre>Submit Login<br>    Click Button    //button[@data-test=&quot;sign-in-sign-in-button&quot;]</pre><pre>Confirm Page Should Be Open<br>    Wait Until Element Contains     //*[@data-test=&quot;confirm-sign-up-header-section&quot;]//span   Confirm</pre><pre>SignIn Page Should Be Open<br>    Wait Until Element Contains     //*[@data-test=&quot;sign-in-header-section&quot;]//span   Sign in to your account</pre><pre>User Page Should Be Open<br>    Wait Until Page Contains    Welcome</pre><p>Let’s break that down a bit.</p><h3>Querying pages with Selenium</h3><p>The selenium plugin adds many keywords to our test suite. We can call them from the resource file to query the playground webapp. We can use css style selectors (xpath) in selenium like so:</p><pre>Submit Login<br>    Click Button    //button[@data-test=&quot;sign-in-sign-in-button&quot;]</pre><p>This would find and click an HTML element that matches:</p><pre>&lt;button data-test=&quot;sign-in-sign-in-button&quot;&gt;Submit&lt;/button&gt;</pre><p>The MailSlurp playground app uses [data-test] attributes to allow for easy acceptance testing that doesn&#39;t rely on constant class or ID DOM attributes.</p><h3>Calling custom Python functions</h3><p>You may be thinking “where is the <em>actual code</em> in all this?”. Let’s get to that. You can call custom functions by including the library like we did in the resource.robot file. Note: the file and class name must be the same. Robot translates method names to keywords by replacing _ underscores with spaces. So the def create_inbox(self): function defining in MailSlurp.py becomes the Create Inbox keywords.</p><p>The MailSlurp create inbox function creates a real email address and returns an inbox entity with an ID and an email address.</p><pre>def create_inbox(self):<br>    with mailslurp_client.ApiClient(self.configuration) as api_client:<br>        # create an inbox using the inbox controller<br>        api_instance = mailslurp_client.InboxControllerApi(api_client)<br>        inbox = api_instance.create_inbox()<br>        return inbox</pre><p>The code inside resource.robot that makes this function and its return object available in tests is this:</p><pre>*** Keywords ***<br>Create Email Address<br>    ${inbox}    Create Inbox<br>    [Return]    ${inbox}</pre><p>This is the custom robot syntax and it assigns the result of the create_inbox function to a local variable before returning it. Inside a test we can call it like this:</p><pre>*** Test Cases ***<br>Sign Up With New Email Address<br>    ${inbox}    Create Email Address</pre><p>Now that we can call MailSlurp and Selenium keywords let us write a test for the full sign up process.</p><h3>Writing Robot tests</h3><p>Create a file called test.robot. Add the settings header to include our resource.robot file so we can access all the keywords.</p><pre>*** Settings ***<br>Documentation     Test user sign-up with MailSlurp and Robot<br>Resource          resource.robot</pre><h3>Our application flow</h3><p>Next we need to test the user sign up and verification process. To recap, the process we wish to test is:</p><ul><li>create a unique email address for the test</li><li>sign up for the playground app using the email address</li><li>receive and extract a confirmation code via email</li><li>submit the verification code and confirm user</li><li>sign in to the app and view the happy dog</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*89cHeSuH4jy-r1N7" /></figure><h3>Our tests</h3><p>Based on the custom functions in MailSlurp.py and the keywords defined in resource.robot we can write a test for the above functionality with the following statements:</p><pre>*** Test Cases ***<br>Sign Up With New Email Address<br>    ${inbox}    Create Email Address<br>    Open Browser To Home Page<br>    Go To SignUp Page<br>    Input Email       ${inbox.email_address}<br>    Input Password    ${TEST_PASSWORD}<br>    Submit Credentials<br>    Confirm Page Should Be Open<br>    ${code}    Wait For Confirmation Code   ${inbox.id}<br>    Log To Console      ${code} extacted<br>    Input Confirmation      ${code}<br>    Submit Confirmation<br>    SignIn Page Should Be Open<br>    Input Username    ${inbox.email_address}<br>    Input Password    ${TEST_PASSWORD}<br>    Submit Login<br>    User Page Should Be Open<br>    [Teardown]    Close Browser</pre><p>Two important functions in this test are:</p><pre># wait for and return an email in an inbox<br>def wait_for_latest_email(self, inbox_id):<br>    with mailslurp_client.ApiClient(self.configuration) as api_client:<br>        # create an inbox using the inbox controller<br>        api_instance = mailslurp_client.WaitForControllerApi(api_client)<br>        email = api_instance.wait_for_latest_email(inbox_id=inbox_id, timeout=60000, unread_only=True)<br>        return email</pre><pre># parse the confirmation code from an email body (adjust for your own use)<br>def extract_email_content(self, email_body):<br>    regex = &#39;Your Demo verification code is ([0-9]{6})&#39;<br>    pattern = re.compile(regex)<br>    matches = pattern.match(email_body)<br>    content = matches.group(1)<br>    return content</pre><p>The wait_for_latest_email function is a unique MailSlurp feature that lets you wait for incoming emails and return the content. We then combine that with a regular expression pattern match to extract the confirmation code from an email of the pattern Your Demo verification code is 123456. In this case the ([0-9]{6}) regular expression is a capture group for the 6 digits that are used as the confirmation code. The extract_email_content returns this value for use in the next steps of the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7uMYZgKAX_AarRqv" /></figure><h3>Testing authentication end-to-end</h3><p>Running the full test suite with python3 -m robot --variable MAILSLURP_API_KEY:your_api_key_here --outputdir results test.robot will create a new email address ending in mailslurp.com, sign up for the playground app, receive the email verification code, confirm the account and log into the app. For full usage see the <a href="https://docs.mailslurp.com/python">Python documentation</a> or the <a href="https://github.com/mailslurp/examples">example code on GitHub</a>.</p><h3>Conclusion</h3><p>Robot Framework and MailSlurp enabled acceptance testing of complex applications by generating real test email accounts. You can test user authentication and sign-up flows, lost password or email verification. See the <a href="https://docs.mailslurp.com/">MailSlurp docs</a> for more information and good luck.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/examples/robotframework-email-testing-python/"><em>https://www.mailslurp.com</em></a><em> on February 7, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a363a5cf4f05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate a Java OpenAPI client and publish it to S3 using Gradle]]></title>
            <link>https://mailslurp.medium.com/generate-a-java-openapi-client-and-publish-it-to-s3-using-gradle-84be931e6c3f?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/84be931e6c3f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 07:22:01 GMT</pubDate>
            <atom:updated>2022-09-13T07:22:01.491Z</atom:updated>
            <content:encoded><![CDATA[<h4>How teams at <a href="https://www.mailslurp.com/">MailSlurp</a> publish and consume client libraries that are generated for each microservice in our cluster.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQffFO8dzlpotUTGRigdBA.png" /><figcaption>You can document APIs and generate strongly-typed client libraries automatically using Gradle.</figcaption></figure><p>Many teams use OpenAPI to document and consume API services. Using OpenAPI tools we can generate strongly typed clients in a wide range of languages. We can then call other services without needing to maintain type definitions in multiple projects.</p><p>With Gradle and Spring we can automate the generation and publication of Swagger codegen clients and distribute the packages via AWS S3. This will give us a private artifact repository that we can connect to in calling services.</p><h3>Annotate your API endpoints</h3><p>The first step in automating your API client generation is to annotate your API endpoints and generate an OpenAPI spec. In Spring we can use springdoc-openapi to describe our endpoints. In a build.gradle.kt file add:</p><pre>dependencies {<br>    implementation(&quot;org.springdoc:springdoc-openapi-ui:1.6.11&quot;)<br>}</pre><p>Then add annotations to your controllers:</p><pre>@Operation(operationId = &quot;deleteJob&quot;, summary = &quot;Delete a scheduled job&quot;) @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(&quot;/jobs/{groupId}/{jobId}&quot;) fun deleteJob(@PathVariable(&quot;groupId&quot;) groupId: String, @PathVariable(&quot;jobId&quot;) jobId: String) {     schedulerFactory.scheduler.deleteJob(JobKey.jobKey(groupId, jobId)) }</pre><h3>Generate an openapi.json spec</h3><p>Next we can use gradle to generate a spec:</p><pre>plugins {  id(&quot;org.springdoc.openapi-gradle-plugin&quot;) version &quot;1.4.0&quot;  id(&quot;org.openapi.generator&quot;) version &quot;6.1.0&quot; }</pre><p>Define a custom openApi task to start Spring and write the OpenAPI spec to the build directory.</p><pre>openApi { customBootRun { args.set(listOf(&quot;--spring.profiles.active=openapi&quot;)) } }</pre><p>When we run ./gradlew generateOpenApiDocs an openapi.json file will be written to the build directory.</p><h3>Generate a client</h3><p>Now we can generate an OpenAPI client using a gradle task:</p><pre>openApiGenerate { generatorName.set(&quot;java&quot;) version.set(System.getenv(&quot;CLIENT_VERSION&quot;)) id.set(&quot;yourid&quot;) groupId.set(&quot;yourgroup&quot;) inputSpec.set(&quot;$buildDir/openapi.json&quot;) outputDir.set(&quot;$buildDir/client&quot;) configOptions.set(mapOf( &quot;dateLibrary&quot; to &quot;java8&quot; )) }</pre><p>Run the command like so ./gradlew openApiGenerate to write a client into the build/client directory. Next we will publish the client to maven via S3.</p><h3>Create a maven S3 repository</h3><p>Create an S3 bucket to use as your maven repository. Now we can publish to S3 with Gradle.</p><h3>Publish to S3 using Gradle</h3><p>We can now use a gradle init script to patch the generated gradle client and add a publishing method for our S3 bucket.</p><pre>allprojects { apply plugin: &#39;java&#39; apply plugin: &#39;maven-publish&#39; publishing { publications { mavenJava(MavenPublication) { from components.java } } repositories { maven { url &quot;s3://my.private.maven&quot; authentication { awsIm(AwsImAuthentication) } } } } }</pre><p>Then to run:</p><pre>cp init-client.gradle build/client/init-client.gradle cd build/client &amp;&amp; ./gradlew --init-script init.gradle publish &amp;&amp; cd -</pre><h3>Voila</h3><p>After this we have shown how to describe your API, generate a client, and publish to S3.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/blog/generate-and-publish-java-openapi-client-with-gradle/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84be931e6c3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing User Sign-Up and Email Confirmation — how to extract MFA tokens during automated testing.]]></title>
            <link>https://mailslurp.medium.com/testing-user-sign-up-and-email-confirmation-how-to-extract-mfa-tokens-during-automated-testing-696943794912?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/696943794912</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[no-code]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Fri, 04 Dec 2020 19:35:25 GMT</pubDate>
            <atom:updated>2020-12-04T19:35:25.231Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing User Sign-Up and Email Confirmation — how to extract MFA tokens during automated testing.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vqe5Id6g2UOXkatT9a93mA.png" /></figure><h3>Background</h3><p>Email is a key component of most modern applications. It identifies users, let’s them sign-up and login, reset passwords and confirm their accounts. Email is important but, strangely, testing processes that rely on email end-to-end can be difficult.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*KZhA_r6cIwxcISRX.png" /><figcaption>How can we test applications that rely on email confirmation? MailSlurp is a free API that makes that possible.</figcaption></figure><h3>Email testing APIs</h3><p>MailSlurp is free to use test <a href="https://www.mailslurp.com/">email account API (opens new window)</a> that was built to solve this problem. It let’s developers create test email accounts on demand in apps and tests, or using a visual dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyRIyOvsb5JSDVcOmFBpcw.png" /></figure><h3>An example project</h3><p>In this post we’ll use a free MailSlurp account to test a typical user sign-up process end-to-end. To do that we will create test email accounts dynamically during each test and use them to sign up for an example website. The <a href="https://www.mailslurp.com/guides/user-signup-playground">MailSlurp Playground</a> will act as our dummy application: a free WebApp that simulates various modern OAuth2 processes.</p><h3>Testing user sign-up</h3><p>Here is what we’ll need to verify in our test</p><ul><li>User can load our application</li><li>User can sign-up using a generated email address</li><li>User receives a confirmation code via email</li><li>User can enter confirmation code and confirm account</li><li>Lastly, user can login and see a welcome screen.</li></ul><p>These steps are common for many applications and may reflect a user sign-up process in your own system.</p><h3>What does our app look like?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YVk7L6UxY5I758ty_7hEA.png" /><figcaption>A demo application for testing</figcaption></figure><p>Anyone can sign-up or login to the site. The application was designed with automated testing in mind and simply displays a happy dog upon successful login.</p><h3>Testing with MailSlurp</h3><blockquote><em>MailSlurp has a REST API and official packages in </em><a href="https://www.mailslurp.com/docs/"><em>Java, PHP, Python, Ruby, C# and more</em></a><em>.</em></blockquote><h3>Project setup</h3><pre>mkdir signup &amp;&amp; cd $_</pre><p>Let’s start by creating a new folder and a few files.</p><p>Assuming we have NodeJS installed let’s add MailSlurp as a dependency via npm.</p><pre>echo &#39;{}&#39; &gt; package.json<br>npm install --save mailslurp-client</pre><blockquote><strong><em>Note</em></strong><em>: MailSlurp is free for personal use but you will need an API Key. Get one by </em><a href="https://app.mailslurp.com/sign-up/"><em>signing-up (opens new window) </em></a><em>.</em></blockquote><h3>Add a test framework</h3><p>Next let’s add to our project. Webdriver goes by the alias wdio and splits itself up across several packages. We&#39;ll add those now.</p><pre>npm install --save @wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/selenium-standalone-service</pre><p>For wdio to run inside a web browser we need to make one available to it. Here we will use Chrome.</p><pre>npm install --save chromedriver wdio-chromedriver-service</pre><h3>Configure Webdriver</h3><p>Next we need to configure wdio using a wdio.conf.js file in the root of our project. This will tell Webdriver where to look for tests and what browser to use. We want out instance to load the Playground app (see baseUrl) and look for tests in a test folder:</p><pre>const config = {<br>  runner: &quot;local&quot;,<br>  path: &quot;/&quot;,<br>  specs: [&quot;test/*.test.js&quot;],<br>  exclude: [],<br>  maxInstances: 10,<br>  capabilities: [<br>    {<br>      maxInstances: 5,<br>      browserName: &quot;chrome&quot;,<br>    },<br>  ],<br>  logLevel: &quot;info&quot;,<br>  bail: 0,<br>  baseUrl: &quot;https://playground.mailslurp.com&quot;,<br>  waitforTimeout: 30000,<br>  connectionRetryTimeout: 90000,<br>  connectionRetryCount: 3,<br>  framework: &quot;mocha&quot;,<br>  services: [&quot;chromedriver&quot;],<br>  reporters: [&quot;spec&quot;],<br>  mochaOpts: {<br>    ui: &quot;bdd&quot;,<br>    timeout: 60000,<br>  },<br>};<br><br>exports.config = config;</pre><h3>Add a test command</h3><p>Lastly, we need a way to run out tests one we have written them. For this we can extend the package.json scripts property to call wdio. Here&#39;s what our package.json file looks like altogether:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;wdio wdio.conf.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@wdio/cli&quot;: &quot;^5.13.2&quot;,<br>    &quot;@wdio/local-runner&quot;: &quot;^5.13.2&quot;,<br>    &quot;@wdio/mocha-framework&quot;: &quot;^5.13.2&quot;,<br>    &quot;@wdio/selenium-standalone-service&quot;: &quot;^5.13.2&quot;,<br>    &quot;@wdio/spec-reporter&quot;: &quot;^5.13.2&quot;,<br>    &quot;chromedriver&quot;: &quot;^78.0.1&quot;,<br>    &quot;mailslurp-client&quot;: &quot;^6.5.0&quot;,<br>    &quot;wdio-chromedriver-service&quot;: &quot;^5.0.2&quot;<br>  }<br>}</pre><p>Now when we run npm test Webdriver will execute any files ending with .test.js in the test directory. Speaking of which, let&#39;s write some!</p><h3>Writing a test</h3><pre>mkdir test<br>touch test/sign-up.test.js</pre><p>Wdio is configured to find tests in a test durectory so let&#39;s create that and add a test to it.</p><h3>Defining test requirements</h3><p>Before we write our test logic let’s review what we want to achieve. We want to test that our app (the Playground) has a functioning user sign-up feature (a critical component of any application). For this we will need to perform the following actions:</p><ul><li>Sign up as a new user</li><li>Confirm the users account</li><li>Login and see a doggy welcome</li></ul><h3>Special needs (why we use a email testing API)</h3><p>Most of these steps are pretty standard for end-to-end testing but sign-up and confirmation are special:</p><ul><li>Sign up will require a <strong>unique email address</strong> each time we run the test</li><li>Confirmation will require that we <strong>fetch and extract a confirmation code</strong> sent to our user’s email address</li></ul><p>Luckily, MailSlurp helps with all that.</p><p>With MailSlurp we can create test email accounts and then send and <em>receive</em> emails from them from within tests. That will allow us to create new email addresses for each test run (so that they are unique and empty) and receive and extract the confirmation code for use in the email confirmation step!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FGe86XF8AVY1KE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FGe86XF8AVY1KE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FGe86XF8AVY1KE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="272" frameborder="0" scrolling="no"><a href="https://medium.com/media/143ef701e77ee72de6fb023bcacc6bad/href">https://medium.com/media/143ef701e77ee72de6fb023bcacc6bad/href</a></iframe><h3>Generating test email accounts</h3><p>MailSlurp makes <a href="https://www.mailslurp.com/">generating dynamic test email accounts</a> on demand easy.</p><p>First <a href="https://app.mailslurp.com/">obtain your API Key</a> and configure a MailSlurp client to use it.</p><pre>const MailSlurp = require(&quot;mailslurp-client&quot;).default;<br>const apiKey = process.env.API_KEY;<br>const mailslurp = new MailSlurp({ apiKey });</pre><p>Then to create a new randomized test email address invoke the createInbox function.</p><pre>const { emailAddress, id } = await mailslurp.createInbox();</pre><blockquote><em>You can specify an address by passing the </em><em>emailAddress parameter and using a custom domain you own. Unspecified email addresses will be randomly assigned under the </em><em>@mailslurp.com domain.</em></blockquote><h3>Testing user sign-up with disposable email addresses</h3><pre>const assert = require(&quot;assert&quot;);<br><br>describe(&quot;sign up page&quot;, () =&gt; {<br>  it(&quot;can load playground app&quot;, async () =&gt; {<br>    await browser.url(https://medium.com/&quot;/&quot;);<br>    await browser.setWindowSize(1200, 1200);<br>  });<br>});</pre><p>Now that we know how to create email addresses on demand with MailSlurp we can write a test that loads the Playground, creates an email account and then uses it to sign-up.</p><p>Here’s the first step for our test:</p><pre>it(&quot;can load the sign-up section&quot;, async () =&gt; {<br>  await $(&#39;[data-test=&quot;sign-in-create-account-link&quot;]&#39;).then((e) =&gt; e.click());<br>  await $(&quot;.sign-up-header-section&quot;)<br>    .then((e) =&gt; e.getText())<br>    .then((text) =&gt; assert.strictEqual(text, &quot;Testable Sign Up Form&quot;));<br>});</pre><p>The above loads the Playground — that’s it. Next we need to navigate to the sign-up form by clicking a link. Then we assert that we are in the right location. We add the following to the same test:</p><p>Let’s test this now to see if it works as we expect.</p><pre>API_KEY=your-mailslurp-api-key npm run test</pre><p>We should see Chrome launch, the sign-up page load and the test complete with successful output:</p><pre>[chrome  linux #0-0] Running: chrome on linux<br>[chrome  linux #0-0]<br>[chrome  linux #0-0] sign up page<br>[chrome  linux #0-0]    ✓ can load playground app<br>[chrome  linux #0-0]    ✓ can load the sign-up section<br>[chrome  linux #0-0]<br>[chrome  linux #0-0] 2 passing (607ms)<br><br><br>Spec Files:	 1 passed, 1 total (100% completed) in 00:00:01</pre><blockquote><em>If your Chromedriver complains you may need to install a version that matches the version of Chrome on your computer.</em></blockquote><h3>Signing up</h3><p>Ok, it works. Now for the fun stuff. Let’s sign up a new user.</p><pre>let inbox;<br>let password = &quot;test-password&quot;;<br><br>it(&quot;can sign-up with test email account&quot;, async () =&gt; {<br>  // create a new email address for the test run<br>  inbox = await mailslurp.createInbox();<br><br>  // fill out and submit the new user form<br>  await $(&#39;[name=&quot;email&quot;]&#39;).then((e) =&gt; e.setValue(inbox.emailAddress));<br>  await $(&#39;[name=&quot;password&quot;]&#39;).then((e) =&gt; e.setValue(password));<br>  await $(&#39;[data-test=&quot;sign-up-create-account-button&quot;]&#39;).then((e) =&gt; e.click());<br>});</pre><p>Running that test should fill out a form like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkST7fSFH6XQEb04psooOw.png" /></figure><h3>Capturing email confirmation code in tests</h3><p>So we have successfully signed up a user using the test email address we created. Now we should see a confirmation page that asks us to enter a code that has been emailed to the address that we used.</p><blockquote><em>MailSlurp allows use to receive emails in tests!</em></blockquote><p>To enter the confirmation code let’s fetch the expected email using MailSlurp, extract the code, and enter it into the form:</p><pre>it(&quot;can fetch confirmation code&quot;, async () =&gt; {<br>  // fetch the email from mailslurp<br>  const email = await mailslurp.waitForLatestEmail(inbox.id);<br><br>  // verify that it contains the code<br>  assert.strictEqual(/verification code is/.test(email.body), true);<br><br>  // extract the confirmation code<br>  code = /([0-9]{6})$/.exec(email.body)[1];<br>});<br><br>it(&quot;can enter confirmation code and confirm user&quot;, async () =&gt; {<br>  await $(&#39;[name=&quot;code&quot;]&#39;).then((e) =&gt; e.setValue(code));<br>  await $(&#39;[data-test=&quot;confirm-sign-up-confirm-button&quot;]&#39;).then((e) =&gt;<br>    e.click()<br>  );<br>});</pre><p>Voila, the test passes, the user is confirmed and we see the sign-in screen. The most important parts of the test above are the lines that fetch the confirmation email and extract the code. The email that is sent looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*YJozoBOyb7HbsoZTDb2_DA.png" /></figure><p>To receive the email in our test we use the waitForLatestEmail method and pass the id of the inbox that we created during that test run. This will return the first email in the inbox or wait for one to be received.</p><p>To extract the verification code we use a regex that matches 6 digits and apply that to the email body.</p><pre>\code = /([0-9]{6})$/.exec(email.body)[1];</pre><h3>Logging in with confirmed account</h3><p>Lastly, let’s test that the confirmed user can sign-in and see a welcome screen. The welcome screen looks a bit like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*B8Nd_KlA4ExETYeCaJOLhw.png" /></figure><p>Here is the code to login in a verify the happy dog is present:</p><pre>it(&quot;can log in with confirmed account&quot;, async () =&gt; {<br>  // assert we see the sign in form<br>  await $(&#39;[data-test=&quot;sign-in-header-section&quot;]&#39;)<br>    .then((e) =&gt; e.getText())<br>    .then((text) =&gt; assert.strictEqual(text, &quot;Sign in to your account&quot;));<br><br>  // fill out username (email) and password<br>  await $(&#39;[name=&quot;username&quot;]&#39;).then((e) =&gt; e.setValue(inbox.emailAddress));<br>  await $(&#39;[name=&quot;password&quot;]&#39;).then((e) =&gt; e.setValue(password));<br><br>  // submit<br>  await $(&#39;[data-test=&quot;sign-in-sign-in-button&quot;]&#39;).then((e) =&gt; e.click());<br>});<br><br>it(&quot;shows the successful greeting&quot;, async () =&gt; {<br>  await $(&#39;[data-test=&quot;greetings-nav-bar&quot;]&#39;)<br>    .then((e) =&gt; e.getText())<br>    .then((text) =&gt; assert.strictEqual(/Hello/.test(text), true));<br>});</pre><h3>In summary</h3><p>This post demonstrating how you can truly end-to-end test email related processes like user sign-up, email confirmation, and login. It used Webdriver to run the tests but the only required aspect is an email API provider like <a href="https://www.mailslurp.com/">MailSlurp (opens new window)</a>. MailSlurp is free for personal use and will let you and your team test every crucial aspect of your app. Give it a go today!</p><h3>Code samples</h3><p>As always full code samples for this post are available <a href="https://github.com/mailslurp/examples">on GitHub (opens new window)</a>.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/guides/test-user-sign-up-with-test-email-accounts/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=696943794912" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Email Testing in 5 Minutes! Send and receive emails in CI and code.]]></title>
            <link>https://mailslurp.medium.com/automated-email-testing-in-5-minutes-send-and-receive-emails-in-ci-and-code-dfa94315ae60?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa94315ae60</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Fri, 04 Dec 2020 19:22:16 GMT</pubDate>
            <atom:updated>2020-12-04T19:22:16.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBOWGEwU-6Lsg8hJsLvhsg.png" /><figcaption>Email APIs let you create email addresses on demand during automated tests.</figcaption></figure><h3>Why?</h3><p>Many applications rely on email addresses in some way: for user sign-up, account verification, notifications, communication and more. In order to truly test these features end-to-end one needs access to real email addresses in code. That is what <a href="http://www.mailslurp.com/developers">MailSlurp</a> enables: real private inboxes that can send and receive email in applications and tests.</p><h3>Basics</h3><p>In testing it is best to create all the entities you need each test run. This ensures that you start with a blank slate each time.</p><h3>Environments</h3><p><a href="https://www.mailslurp.com/">MailSlurp</a> has a REST API and <a href="https://www.mailslurp.com/docs/">SDKs</a> in Javascript, PHP, Java, Python, Go and more so it integrates into most test platforms.</p><p>You can create a test in Javascript like so:</p><pre>npm install --save mailslurp-client</pre><p>Then instantiate a client:</p><pre>const MailSlurp = require(&quot;mailslurp-client&quot;).default;</pre><p>Or with Javascript ES6 style imports (Typescript also supported):</p><pre>import { MailSlurp } from &quot;mailslurp-client&quot;;</pre><p>Finally, configure the client with a <a href="https://app.mailslurp.com/">free API Key</a></p><pre>const mailSlurp = new MailSlurp({ apiKey: &quot;your_key_here&quot; });</pre><h3>Common use cases</h3><p>In your tests use the inbox’s email address if you want to:</p><ul><li>test that your systems can send emails (and they are valid when received)</li><li>test that your system can receive emails (and that appropriate actions are taken)</li><li>test email related processes like user sign-up, password reset, newsletter subscription, transactional emails etc using real email addresses</li></ul><p>This guide assumes you have instantiated a Javascript MailSlurp client. For installation see <a href="https://www.mailslurp.com/guides/getting-started">getting started</a>.</p><h3>Creating inboxes</h3><p>The first step for any test is to create a new empty inbox with a randomly assigned email address. Use the createInbox() method for this purpose.</p><pre>const inbox = await mailslurp.createInbox();</pre><p>The resulting inbox will look something like this:</p><pre>{<br>  &quot;id&quot;: &quot;123&quot;,<br>  &quot;emailAddress&quot;: &quot;123@mailslurp.com&quot;<br>}</pre><h3>Sending emails</h3><p>You can send an email easily using the sendEmail() methods with a given inbox id.</p><pre>await mailslurp.sendEmail(inboxId, { to: [&quot;user@test.com&quot;], body: &quot;Hello&quot; });</pre><h3>Receiving emails</h3><p>To receive emails in tests use the waitFor methods <strong>after</strong> your app or test has done something that sends an email to your inbox.</p><p>Note: waitFor methods hold a connection open until a conditon is met within the default or specified timeout. You must ensure that your test-suite has an appropriately high timeout to permit this.</p><p>There are many waitFor methods available. The simplest is waitForLatestEmail which has the following signature:</p><pre>waitForLatestEmail(inboxId?: string, timeout?: number): Promise&lt;Email&gt;</pre><p>This will either return the latest email <strong>OR</strong> hold open the connection until a email is received. You can adjust the timeout period with a millisecond value as the second parameter. Here is an example:</p><pre>test(&#39;app sends welcome`, async () =&gt; {<br><br>  const inbox = await mailslurp.createInbox();<br><br>  await myApp.sendWelcome(inbox.emailAddress);<br><br>  const welcome = await mailslurp.waitForLatestEmail(inbox.id)<br><br>  expect(welcome.subject).toBe(&#39;Welcome!&#39;)<br>})</pre><h3>Extracting email content</h3><p>MailSlurp email responses split a message into various properties such as to, subject and body. The body is the text content of an email in string form. The full body is available like so:</p><pre>const email = await mailslurp.waitForLatestEmail(inbox.id);<br>console.log(email.body);</pre><p>If you want to extract a section of the message body for use in further test steps you can do so easily with a regular expression.</p><pre>// fetch an email<br>const email = await mailslurp.waitForLatestEmail(inbox.id);<br><br>// execute a regular express capture group on the body and<br>// destructure the matching group into a variable<br>const [_, verificationCode] = /your code is &quot;([0-9]{6})&quot;/g.exec(email.body);<br><br>// do something with code like verifying an account<br>myApp.confirmUser(verificationCode);</pre><h3>Special characters</h3><p>Be aware that mail providers sometimes use esoteric SMTP character encodings for common UTF8 characters such as ?, &amp;, and =. MailSlurp tries to correct most of these but if your regex matches aren&#39;t finding results you expect on the first attempt try inspecting the body for bad characters. Use HTML entities in your regular expression if this is the case.</p><p>Here is an example that extracts a code number from the body of an HTML message containing http://test.com?code=123 from an old mail server.</p><pre>// notice that &quot;=&quot; is replaced with &quot;&amp;#x3D;&quot; HTML entity<br>const [_, code] = /\?code&amp;#x3D;([^&#39;&quot;]+)/g.exec(body);</pre><h3>Test Framework integrations</h3><p>MailSlurp is cross platform and has libraries for many different languages. Here are some notes for popular test frameworks: ]</p><h3>CypressJS</h3><p>MailSlurp works well with Cypress JS meaning you can create email addresses and send and receive email in end-to-end tests.</p><p>It is important to <strong>set default timeouts</strong> in cypress.json so that MailSlurp&#39;s waitFor methods can wait for emails.</p><pre>{<br>  &quot;defaultCommandTimeout&quot;: 30000,<br>  &quot;requestTimeout&quot;: 30000<br>}</pre><p>It is recommended to use MailSlurp with custom Cypress commands. These can be used to wrap MailSlurp’s async functions for use with Cypress async style.</p><p>For instance, in cypress/support/commands.js:</p><pre>const { MailSlurp } = require(&quot;mailslurp-client&quot;);<br><br>Cypress.Commands.add(&quot;createInbox&quot;, () =&gt; {<br>  return mailslurp.createInbox();<br>});</pre><p>Then in tests:</p><pre>it(&quot;can sign up&quot;, () =&gt; {<br>  cy.createInbox((inbox) =&gt; {<br>    cy.get(&quot;#sign-up-email&quot;).type(inbox.emailAddress);<br>    // etc<br>  });<br>});</pre><h3>Next steps</h3><p>For more examples and guides see mailslurp.com. Thanks!</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/guides/testing/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa94315ae60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Email APIs in C# and  Selenium (testing user sign-up with examples)]]></title>
            <link>https://mailslurp.medium.com/test-email-apis-in-c-and-selenium-testing-user-sign-up-with-examples-893c1dda189b?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/893c1dda189b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Fri, 01 May 2020 19:40:36 GMT</pubDate>
            <atom:updated>2020-05-01T19:40:36.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>Test Email APIs in C# and Selenium (testing user sign-up with examples)</h3><h4><em>Selenium is an integration test framework with C# bindings. We can use it with test email accounts to send and receive emails from code and tests.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*Da02VGatq8p0OHlK.png" /></figure><p>If you write .NET applications you probably deal with email addresses at some point: for user sign-up, email newsletters, password resets and more. If you want to test this functionality end-to-end you need test email accounts.</p><p><a href="https://www.mailslurp.com/">MailSlurp</a> is a free API that lets you create email addresses in C# then send and receive emails with them. This article will show you how to test a web applications user sign-up using Nunit, .NET Core 2.1, Selenium and Firefox Gecko Driver.</p><h3>Example application</h3><p>For an example of using emails in selenium with .NET we will use a dummy web app hosted at <a href="https://playground.mailslurp.com/">https://playground.mailslurp.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gZXuQ_0MWXOoeDC2.png" /></figure><p>This app has a real sign-up process. It lets users sign-up with an email address, then it sends them a confirmation code via email. The user can then submit the confirmation code and confirm their account. Finally the user can sign in and see a welcome screen.</p><p>We’ll test this process end to end. Full <a href="https://github.com/mailslurp/examples/">source code available on GitHub</a>.</p><h3>Writing a test</h3><p>To test the Playgrounds authentication process with real email addresses lets set up a .NET Core project.</p><h3>Setup</h3><p>First you need Firefox and the Selenium Gecko Driver. You can install them with choco or download them manually and add them to your Path.</p><pre>choco install firefox c<br>hoco install selenium-gecko-driver</pre><h3>Add project dependencies</h3><p>Create a new .NET Core project and add the following dependencies in YourProject.csproj:</p><pre>&lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;mailslurp&quot; Version=&quot;7.1.3&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.5.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;nunit&quot; Version=&quot;3.12.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;NUnit3TestAdapter&quot; Version=&quot;3.16.1&quot;&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>    &lt;/PackageReference&gt;<br>    &lt;PackageReference Include=&quot;Selenium.WebDriver&quot; Version=&quot;3.141.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Selenium.WebDriver.GeckoDriver&quot; Version=&quot;0.26.0.1&quot; /&gt;<br>  &lt;/ItemGroup&gt;</pre><h3>Create test file</h3><p>Next create an Nunit test:</p><pre>using System;<br>using System.Text.RegularExpressions;<br>using mailslurp.Api;<br>using mailslurp.Client;<br>using mailslurp.Model;<br>using NUnit.Framework;<br>using OpenQA.Selenium;<br>using OpenQA.Selenium.Firefox;<br><br>// Example usage for MailSlurp email API plugin<br>namespace ExampleService.Tests<br>{<br>    <br>    [TestFixture]<br>    public class ExampleTest<br>    {<br>        // tests will go here<br>    }<br>}</pre><p>Next we need to configure Selenium. We will add a FirefoxDriver and tell it to start before our tests. Then we’ll add a shutdown method after the tests have finished. Put the following inside the ExampleTest class:</p><pre>private static IWebDriver _webdriver;<br>private static Configuration _mailslurpConfig;<br><br>// get a MailSlurp API Key free at https://app.mailslurp.com<br>private static readonly string YourApiKey = &quot;your-api-key-here&quot;;<br><br>private static readonly long TimeoutMillis = 30_000L;<br><br>[SetUpFixture]<br>public class NunitSetup<br>{<br>    // runs once before any tests<br>    [OneTimeSetUp]<br>    public void SetUp()<br>    {<br>        // set up the webdriver for selenium<br>        var timeout = TimeSpan.FromMilliseconds(TimeoutMillis);<br>        var service = FirefoxDriverService.CreateDefaultService()<br>        _webdriver = new FirefoxDriver(service, new FirefoxOptions(), timeout);<br>        _webdriver.Manage().Timeouts().ImplicitWait = timeout;<br>        <br>        // configure mailslurp with API Key<br>        Assert.NotNull(YourApiKey);<br>        _mailslurpConfig = new Configuration();<br>        _mailslurpConfig.ApiKey.Add(&quot;x-api-key&quot;, YourApiKey);<br>    }<br><br>    // runs once after all tests finished<br>    [OneTimeTearDown]<br>    public void Dispose()<br>    {<br>        // close down the browser<br>        _webdriver.Quit();<br>        _webdriver.Dispose();<br>    }<br>}</pre><p>Now we can write some tests. So let’s load the playground app and click the sign-up button:</p><pre>[Test, Order(1)]<br>public void CanLoadPlaygroundAppInBrowser_AndClickSignUp()<br>{<br>    // open the dummy authentication app and assert it is loaded<br>    _webdriver.Navigate().GoToUrl(&quot;https://playground.mailslurp.com&quot;);<br>    Assert.AreEqual(&quot;React App&quot;, _webdriver.Title);<br>    <br>    // can click the signup button<br>    _webdriver.FindElement(By.CssSelector(&quot;[data-test=sign-in-create-account-link]&quot;)).Click();<br>}</pre><h3>Create test email accounts</h3><p>Next we need to start a user sign-up. We will need a new test email account first. Create one with MailSlurp then use it to fill the sign-up form:</p><pre>private static Inbox _inbox;<br><br>[Test, Order(2)]<br>public void CanCreateTestEmail_AndStartSignUp()<br>{<br>    // first create a test email account<br>    var inboxControllerApi = new InboxControllerApi(_mailslurpConfig);<br>    _inbox = inboxControllerApi.CreateInbox();<br>    <br>    // inbox has a real email address<br>    var emailAddress = _inbox.EmailAddress;<br>    <br>    // next fill out the sign-up form with email address and a password<br>    _webdriver.FindElement(By.Name(&quot;email&quot;)).SendKeys(emailAddress);<br>    _webdriver.FindElement(By.Name(&quot;password&quot;)).SendKeys(Password);<br>    <br>    // submit form<br>    _webdriver.FindElement(By.CssSelector(&quot;[data-test=sign-up-create-account-button]&quot;)).Click();<br>}</pre><p>If we run the test the result should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GZIdEJp4U2u96SP_.png" /></figure><h3>Receive confirmation email</h3><p>Once the sign-up form is submitted the playground app will send a confirmation code to the email address. We can wait for the email to arrive using MailSlurp.</p><pre>private static Email _email;<br><br>[Test, Order(3)]<br>public void CanReceiveConfirmationEmail()<br>{<br>    // now fetch the email that playground sends us<br>    var waitForControllerApi = new WaitForControllerApi(_mailslurpConfig);<br>    _email = waitForControllerApi.WaitForLatestEmail(inboxId: _inbox.Id, timeout: TimeoutMillis, unreadOnly: true);<br><br>    // verify the contents<br>    Assert.IsTrue(_email.Subject.Contains(&quot;Please confirm your email address&quot;));<br>}</pre><h3>Extract content and confirm</h3><p>Next let’s find the verification code in the email and submit it to the confirmation screen:</p><pre>private static String _confirmationCode;<br><br>[Test, Order(4)]<br>public void CanExtractConfirmationCode()<br>{<br>    // we need to get the confirmation code from the email<br>    var rx = new Regex(@&quot;.*verification code is (\d{6}).*&quot;, RegexOptions.Compiled);<br>    var match = rx.Match(_email.Body);<br>    _confirmationCode = match.Groups[1].Value;<br>    <br>    Assert.AreEqual(6, _confirmationCode.Length);<br>}<br><br>[Test, Order(5)]<br>public void CanConfirmUserWithEmailedCode()<br>{<br>    // fill the confirm user form with the confirmation code we got from the email<br>    _webdriver.FindElement(By.Name(&quot;code&quot;)).SendKeys(_confirmationCode);<br>    _webdriver.FindElement(By.CssSelector(&quot;[data-test=confirm-sign-up-confirm-button]&quot;)).Click();<br>}</pre><p>Running the test should look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vKjHf1Mwb8MAXmLk.png" /></figure><h3>Sign in with confirmed user</h3><p>Finally we can test that a confirmed user can sign in. Load the playground again and sign in.</p><pre>[Test, Order(6)]<br>public void CanLoginWithConfirmedUser()<br>{<br>    // load the main page again<br>    _webdriver.Navigate().GoToUrl(&quot;https://playground.mailslurp.com&quot;);<br>    <br>    // login with email and password (we expect it to work now that we are confirmed)<br>    _webdriver.FindElement(By.Name(&quot;username&quot;)).SendKeys(_inbox.EmailAddress);<br>    _webdriver.FindElement(By.Name(&quot;password&quot;)).SendKeys(Password);<br>    _webdriver.FindElement(By.CssSelector(&quot;[data-test=sign-in-sign-in-button]&quot;)).Click();<br><br>    // verify that user can see authenticated content<br>    Assert.IsTrue(_webdriver.FindElement(By.TagName(&quot;h1&quot;)).Text.Contains(&quot;Welcome&quot;));<br>}</pre><p>The login should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*265gn8fQDXvfgzwf.png" /></figure><p>Once logged in the user will be greeted with a welcome message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*cruZyreNSEhNpBpP.png" /></figure><h3>Next steps</h3><p>Selenium is a powerful testing tool. When combined with test email accounts you can test email related processes end-to-end. MailSlurp is free email API with C# bindings. Check out the <a href="https://www.mailslurp.com/docs/csharp/">documentation to get started</a>.</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/examples/test-emails-selenium-dotnet-csharp/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=893c1dda189b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cypress JS Email Plugin —how to test with real email addresses! ]]></title>
            <link>https://mailslurp.medium.com/cypress-js-email-plugin-how-to-test-with-real-email-addresses-ed811d9e98a0?source=rss-fbbb220ffadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed811d9e98a0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cypressio]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[MailSlurp | Email APIs for developers]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 14:22:19 GMT</pubDate>
            <atom:updated>2020-04-28T14:22:19.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to send and receive emails in Cypress integration tests using Javascript and the free MailSlurp library.</h4><h3>What is Cypress Js?</h3><p>Cypress is an amazing end-to-end testing framework. It’s popular, bundles its own chrome browser and is easily extended. Here is a screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebtLWvwbqx91-9GyER_lmw.png" /><figcaption>An example login form being tested with Cypress.</figcaption></figure><p>Cypress lets you test many parts of a website or web application with a browser in an automated way. It’s like Selenium but a lot more user-friendly.</p><h3>Testing with real email addresses</h3><p>Many application use emails for account login and creation. Testing logins with Cypress is easy if you have a designated test user — but what about sign ups?</p><p>Email sign up has to be the most important aspect of any application and without access to unique, private email addresses end-to-end testing is difficult.</p><p>Luckily there’s <a href="https://www.mailslurp.com/">MailSlurp</a>, a free API that lets you create real, randomized email addresses on demand. It also lets you send and receive email programmatically — perfect for end-to-end testing user sign-up flows!</p><h3>An example</h3><p>To demonstrate Cypress testing we’ll use the MailSlurp Authentication Playground app. It’s a dummy React application that has a user sign-up process. To test this process end-to-end we will:</p><ul><li>Load the playground in Cypress</li><li>Create a test email address with MailSlurp</li><li>Sign up for using the email address</li><li>Receiving a confirmation email</li><li>Extract the confirmation code and confirm the user</li></ul><h3>Setup Cypress</h3><p>To setup make sure you have NodeJS installed then run:</p><p>npm install --save cypress mailslurp</p><p>Your package.json should look something like this:</p><pre>{<br>  &quot;dependencies&quot;: {<br>    &quot;cypress&quot;: &quot;^4.4.1&quot;,<br>    &quot;mailslurp-client&quot;: &quot;^8.7.8&quot;<br>  }<br>}</pre><p>Next we need to create a cypress.json file. We will set defaultCommandTimeout and requestTimeout to 30 seconds so that our tests have time to wait for emails to be sent or received. We&#39;ll also add some viewport dimensions to the Cypress browser.</p><p>Note for this example we also include our MailSlurp API Key in an env section of the cypress.json file. We can read that later in tests using Cypress.env(&quot;API_KEY&quot;).</p><pre>{<br>  &quot;defaultCommandTimeout&quot;: 30000,<br>  &quot;requestTimeout&quot;: 30000,<br>  &quot;viewportHeight&quot;: 800,<br>  &quot;viewportWidth&quot;: 800,<br>  &quot;env&quot;: {<br>    &quot;API_KEY&quot;: &quot;put-your-mailslurp-key-here&quot;<br>  }<br>}</pre><h3>Setup MailSlurp</h3><p>In order to use MailSlurp with Cypress we will define some custom commands.</p><p>To do that create a cypress/support directory and add index.js and commands.js.</p><pre>cypress <br>  └── support <br>    └── commands.js <br>    └── index.js</pre><p>Inside index.js import the commands file.</p><pre>// cypress/support/index.js<br>import &quot;./commands&quot;;</pre><p>Now inside commands let’s import and configure a MailSlurp client — this will let us send and receive emails. Make sure you have <a href="https://www.mailslurp.com/">a free API Key</a>.</p><pre>// cypress/support/commands.js<br>const { MailSlurp } = require(&quot;mailslurp-client&quot;);<br><br>const apiKey = &quot;YOUR_MAILSLURP_API_KEY&quot;;// or Cypress.env(&quot;API_KEY&quot;)<br>const mailslurp = new MailSlurp({ apiKey });</pre><p>Next we will add commands to create email addresses and receive emails:</p><pre>Cypress.Commands.add(&quot;createInbox&quot;, () =&gt; {<br>  return mailslurp.createInbox();<br>});<br><br>Cypress.Commands.add(&quot;waitForLatestEmail&quot;, inboxId =&gt; {<br>  return mailslurp.waitForLatestEmail(inboxId);<br>});</pre><p>Now in Cypress tests we can do the following:</p><pre>cy.createInbox().then(inbox =&gt; {<br>  console.log(inbox);<br>  // { id: &#39;...&#39;, emailAddress: &#39;...&#39; }<br>});</pre><p>Or:</p><pre>cy.waitForLatestEmail(inbox.id).then(email =&gt; {<br>  console.log(email);<br>  // { subject: &#39;...&#39;, body: &#39;...&#39; }<br>});</pre><h3>Create test structure</h3><p>So in order to test a sign-up flow end-to-end we need an integration test. Create a test spec in the cypress/integration folder structure:</p><pre>touch cypress/integration/example.spec.js</pre><p>The test should be located as follows:</p><pre>cypress <br>└── integration <br>└── example.spec.js</pre><p>Inside integration/example.spec.js let&#39;s write our first test.</p><h3>Writing a test</h3><p>Let’s start simple and write a test to load the MailSlurp playground app in Cypress.</p><p>That would look a little like this:</p><pre>describe(&quot;Sign up&quot;, () =&gt; {<br>  it(&quot;can load oauth demo site&quot;, () =&gt; {<br>    cy.visit(&quot;https://playground.mailslurp.com&quot;);<br>    cy.contains(&quot;Sign in to your account&quot;);<br>  });<br>});</pre><p>Next we want to click a sign up button to begin the sign up process.</p><pre>it(&quot;can click sign up link&quot;, () =&gt; {<br>  cy.get(&#39;[data-test=&quot;sign-in-create-account-link&quot;]&#39;).click();<br>  cy.contains(&quot;Testable Sign Up Form&quot;);<br>});</pre><p>The end result for our test looks like this:</p><pre>describe(&quot;Sign up&quot;, () =&gt; {<br>  it(&quot;can load oauth demo site&quot;, () =&gt; {<br>    cy.visit(&quot;https://playground.mailslurp.com&quot;);<br>    cy.contains(&quot;Sign in to your account&quot;);<br>  });<br><br>  it(&quot;can click sign up link&quot;, () =&gt; {<br>    cy.get(&#39;[data-test=&quot;sign-in-create-account-link&quot;]&#39;).click();<br>    cy.contains(&quot;Testable Sign Up Form&quot;);<br>  });<br>});</pre><h3>Running tests</h3><p>To run the test run npx cypress run. Cypress will open:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LOgfOeEaYVAUxZdY.png" /></figure><p>Click the spec runs our test. Our clicked Cypress loads the Playground app and asserts that a sign-in message is displayed on the page, it then clicks the sign-up link.</p><p>The output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0OY-aDJ3KvPI_V_1.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DCaV70mKvTRMWwaW.png" /></figure><h3>Testing with emails in Cypress</h3><p>Now let’s integrate email address into our test using . MailSlurp requires an api key but it’s free for personal use so <a href="https://app.mailslurp.com/">sign up to get one</a>.</p><p>Once you’ve sign up we can extend Cypress with a command to creates new email address when we need them.</p><h3>Generate test email accounts in Cypress</h3><p>To extend Cypress first create a support folder in the cypress directory and place an index.js and a command.js inside it. Like so:</p><pre>cypress <br>├── integration <br>│ └── example.spec.js <br>└── support<br>  ├── commands.js <br>  └── index.js</pre><p>Inside index.js import the commands.</p><pre>import &#39;./commands&#39;</pre><p>Now let’s set up a command called createInbox inside commands.js that calls MailSlurp and creates an email address on demand.</p><pre>const { MailSlurp } = require(&quot;mailslurp-client&quot;);<br><br>Cypress.Commands.add(&quot;createInbox&quot;, () =&gt; {<br>  // instantiate MailSlurp<br>  const mailslurp = new MailSlurp({ apiKey: Cypress.env(&quot;API_KEY&quot;) });<br>  // return { id, emailAddress } or a new randomly generated inbox<br>  return mailslurp.createInbox();<br>});</pre><h3>Using our createInbox command</h3><p>Now that we have a Cypress command that returns a new email address we can put it all together in our sign up test. Inside the same describe method add the following:</p><pre>const password = &quot;test-password&quot;;<br>let inboxId;<br>let emailAddress;<br><br>it(&quot;can generate a new email address and sign up&quot;, () =&gt; {<br>  // see commands.js custom commands<br>  cy.createInbox().then(inbox =&gt; {<br>    // verify a new inbox was created<br>    assert.isDefined(inbox);<br><br>    // save the inboxId for later checking the emails<br>    inboxId = inbox.id;<br>    emailAddress = inbox.emailAddress;<br><br>    // sign up with inbox email address and the password<br>    cy.get(&quot;input[name=email]&quot;).type(emailAddress);<br>    cy.get(&quot;input[name=password]&quot;).type(password);<br>    cy.get(&#39;[data-test=&quot;sign-up-create-account-button&quot;]&#39;).click();<br>  });<br>});</pre><p>Notice that we destructure the returned value from our helper command.</p><pre>cy.newEmailAddress().then(({ emailAddress }) =&gt; {<br>  /* do stuff */<br>});</pre><p>Now we can run our tests again</p><p>npx cypress run</p><p>Cypress loads our login screen and enters a real address that was generated with MailSlurp. We then see a confirm screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RLexBUjpW-tocPbE.png" /></figure><h3>Receive confirmation email</h3><p>Once we have submitted our new user sign-up the Playground will send a confirmation email with a code that we need to enter. We can receive this email using MailSlurp:</p><pre>let code;<br>it(&quot;can receive the confirmation email and extract the code&quot;, () =&gt; {<br>  // wait for an email in the inbox<br>  cy.waitForLatestEmail(inboxId).then(email =&gt; {<br>    // verify we received an email<br>    assert.isDefined(email);<br><br>    // verify that email contains the code<br>    assert.strictEqual(/verification code is/.test(email.body), true);<br><br>    // extract the confirmation code (so we can confirm the user)<br>    code = /([0-9]{6})$/.exec(email.body)[1];<br>  });<br>});</pre><p>Running the tests shows that Cypress waits for and extracts the email content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6yKrp9lnw8avtdCV.png" /></figure><h3>Confirm the user</h3><p>Finally we can use the extracted email code to confirm the user:</p><pre>let code;<br>it(&quot;can receive the confirmation email and extract the code&quot;, () =&gt; {<br>  // wait for an email in the inbox<br>  cy.waitForLatestEmail(inboxId).then(email =&gt; {<br>    // verify we received an email<br>    assert.isDefined(email);<br><br>    // verify that email contains the code<br>    assert.strictEqual(/verification code is/.test(email.body), true);<br><br>    // extract the confirmation code (so we can confirm the user)<br>    code = /([0-9]{6})$/.exec(email.body)[1];<br>  });<br>});</pre><p>Now we can use Cypress to login with our confirmed email address and password:</p><pre>it(&quot;can log in with confirmed account&quot;, () =&gt; {<br>  cy.contains(&quot;Sign in to your account&quot;);<br>  // fill out username (email) and password<br>  cy.get(&#39;[data-test=&quot;username-input&quot;]&#39;).type(emailAddress);<br>  cy.get(&#39;[data-test=&quot;sign-in-password-input&quot;]&#39;).type(password);<br>  // submit<br>  cy.get(&#39;[data-test=&quot;sign-in-sign-in-button&quot;]&#39;).click();<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jxm6285uzp6XssgH.png" /></figure><p>If successful the Playground will show a picture of a happy dog. Let’s test for that:</p><pre>it(&quot;shows the successful greeting&quot;, () =&gt; {<br>  cy.contains(&quot;Welcome&quot;);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bE9kLuoveCwVnoKn.png" /></figure><h3>Next Steps</h3><p>Testing with real emails means truly testing your app’s most important processes like user sign up and email verification.</p><p>For more information on <a href="https://www.mailslurp.com/docs/">receiving emails in tests</a> see the developers sections.</p><h3>Code Samples</h3><p>As always you can find this and other examples at <a href="https://github.com/mailslurp/examples">https://github.com/mailslurp/examples</a>. Use MailSlurp free and take your end-to-end test coverage to 💯 !</p><p><em>Originally published at </em><a href="https://www.mailslurp.com/examples/cypress-js/"><em>https://www.mailslurp.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed811d9e98a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>