Saturday, 3 February 2018

send email asp.net




firs time use external app to access gmail, google will email security alert

turn less secure app on




home controller

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using email.Models;
using Microsoft.AspNetCore.Http;
using System.Net.Mail;
using System.Text.RegularExpressions;

namespace email.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Index(IFormCollection collection)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress(collection["fromAddress"].ToString() + "@gmail.com");
                mail.Subject = collection["toSubject"].ToString();
                mail.Body = collection["toMessage"].ToString();

                //add sent addresses---------------------------------------------------
                string[] addresses = collection["toAddress"].ToString().Split(';');

                for (int i = 0; i < addresses.Length; i++)
                {
                    var address = addresses[i].Replace(" ", "").Replace("\r\n","");

                    bool valid_address = false;

                    try
                    {
                        valid_address = Regex.IsMatch(address,
                              @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                              @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                              RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
                    }
                    catch (RegexMatchTimeoutException)
                    {
                        valid_address = false;
                    }

                    if (valid_address)
                    {
                        mail.To.Add(address);
                        var address_added = address + "; ";
                        ViewBag.status += address_added;
                    }
                }
                //-------------------------------------------------------------

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential(collection["fromUser"].ToString(), collection["fromPassword"].ToString());
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);

                ViewBag.status += "email sucessfully sent";

                return View();
            }
            catch (Exception ex)
            {
                ViewBag.status = ex.ToString();
                return View();
            }
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

---------------------------------------------------------------------------

home view

@{
    ViewData["Title"] = "Home Page";
}

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#status").html('@ViewBag.status');

        $("#toMessage").css("resize", "none");
    });

    function fromAddress_change() {
        $("#fromUser").val($("#fromAddress").val());
    }

    function onsubmit_check() {

        if ($("#toSubject").val() == "") {

            var sentNoSubject = confirm("send without subject");

            if (sentNoSubject == true) { return true; }
            else { return false; }
        }

        return true;
    }

    $(function () { $("[data-toggle='popover']").popover(); });
</script>

<div class="text-danger" id="status"></div>

<form method="post" onsubmit="return onsubmit_check()">
    <div class="row">
        <h6>
            <label class="col-xs-2">from gmail address </label>
            <input type="text" class="col-xs-8" name="fromAddress" id="fromAddress" onchange="fromAddress_change()" required="required" />
            <label class="col-xs-2">@@gmail.com</label>
        </h6>
    </div>
    <div class="row">
        <h6>
            <label class="col-xs-2">gmail user name </label>
            <input type="text" class="col-xs-8" name="fromUser" id="fromUser" required="required" />
        </h6>
    </div>
    <div class="row">
        <h6>
            <label class="col-xs-2">gmail password </label>
            <input type="password" class="col-xs-8" name="fromPassword" required="required" />
        </h6>
    </div>
    <div class="row">
        <h6>
            <label class="col-xs-2">to email address </label>
            <textarea rows="5" class="col-xs-8" name="toAddress" required="required" placeholder="a@xyz.com; b@xyz.com; c@xyz.com"></textarea>
        </h6>
        <h3><span class="col-xs-2 glyphicon glyphicon-question-sign" title="enter multiple address" data-container="body" data-toggle="popover" data-placement="top" data-content="enter email addresses seperated by semicolon"></span></h3>
    </div>
    <div class="row">
        <h6>
            <label class="col-xs-2">email subject </label>
            <input type="text" class="col-xs-8" name="toSubject" id="toSubject" />
        </h6>
    </div>
    <div class="row">
        <h6>
            <label class="col-xs-2">message </label>
            <textarea rows="10" class="col-xs-8" name="toMessage" id="toMessage"></textarea>
        </h6>
    </div>
    <div class="row">
        <h6>
            <input type="submit" class="col-xs-8 col-xs-offset-2 btn btn-primary btn-xs" value="submit" />
        </h6>
    </div>
</form>

---------------------------------------------------------------------------------


reference:
http://csharp.net-informations.com/communications/csharp-smtp-mail.htm

bootstrap icon
https://www.w3schools.com/bootstrap/bootstrap_ref_comp_glyphs.asp

email regular expression
https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

No comments:

Post a Comment