I am working on a project which is in ASP.NET Core.
In this project users have to confirm their mail before using their panel. I have written this part of code but there is a problem.
When I debug project and I get the confirmation link, copy it and
paste it to browser, mail confirmation goes successful
but
when I send confirmation Url by email to user's mail and user clicks on it to redirect to my website confirmation fails.
I don't understand the issue because it's weird. I have hard coded some part to test it but nothing changed.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
try
{
if (ModelState.IsValid)
{
if (model.ReferralCode != null)
{
var tmpUser = userManager.Users.FirstOrDefault(f => f.IntroductionCode == model.ReferralCode);
if(tmpUser == null)
{
return Json(new { result = "error", target = "register", message = $"No user found with this({model.ReferralCode}) referral code" });
}
}
var user = new ApplicationUser
{
Id = Guid.NewGuid().ToString(),
FullName = model.FullName,
Email = model.Email,
UserName = model.Email,
Balance = 0,
ReferralCode = model.ReferralCode,
IntroductionCode = new Random().RandomString(16),
IsVerified = false
};
var signUpResut = await userManager.CreateAsync(user, model.Password);
if (signUpResut == IdentityResult.Success)
{
var token = await userManager.GenerateEmailConfirmationTokenAsync(user);
var emailActivationUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, verifyToken = token });
new MailHelper(_logger).SendConfirmationEmail(user.FullName,user.Id, user.Email, token);
_logger.Log(LogLevel.Information, $"User {model.Email} Registered Successfully.");
return Json(new { result = "success", target = "register", message = "You have successfully registered. Check your mail to activate account." });
}
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
catch (Exception exc)
{
_logger.Log(LogLevel.Critical, $"Failed Registeration : {exc.Message}");
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
}
here is mail sender code
public bool SendConfirmationEmail(string name, string id, string email, string confirmationToken)
{
try
{
var mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress("***", "***"));
mailMessage.To.Add(new MailboxAddress(name, email));
mailMessage.Subject = "subject";
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={id}&verifyToken={confirmationToken}";
mailMessage.Body = MailBodyMaker($"Click here", "Click here");
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("smtp.gmail.com", 465, true);
smtpClient.Authenticate("***", "****");
smtpClient.Send(mailMessage);
smtpClient.Disconnect(true);
}
return true;
}
catch(Exception exc)
{
_logger.Log(LogLevel.Critical, $"Email sending finished with exception ${exc.Message}");
return false;
}
}
The confirmation link looks like below in debug mode
https://localhost:44323/Account/ConfirmEmail?userId=9bb1a751-813b-48d2-a44c-74fd32a2db9a&verifyToken=CfDJ8A%2FFQtr0XBRFinX98FbsJc5LpPXqjstNllYq%2Br7kr6BHFfA7lBINCCoviE0nqJ6EQc1sJ7RW87jNsaR3fEkEbKoOhemFE62GCrTfn9gEizWV99lZhMrLxJPzGm1u6j3x%2FARoBqVuCVpp34ki0OZM%2BEJi31hNbwyowZ4YwoOnKjMqAOdu2bVG46WfXZBRG9AiOaFNTy326ijQmaTVDNSBl8lQR4gBWkmmRAdkcdFfOasLHD24wyUjmqgkOM2yTJ19Dw%3D%3D
and it looks like below in email body
https://localhost:44323/Account/ConfirmEmail?userId=9bb1a751-813b-48d2-a44c-74fd32a2db9a&verifyToken=CfDJ8A/FQtr0XBRFinX98FbsJc5LpPXqjstNllYq+r7kr6BHFfA7lBINCCoviE0nqJ6EQc1sJ7RW87jNsaR3fEkEbKoOhemFE62GCrTfn9gEizWV99lZhMrLxJPzGm1u6j3x/ARoBqVuCVpp34ki0OZM+EJi31hNbwyowZ4YwoOnKjMqAOdu2bVG46WfXZBRG9AiOaFNTy326ijQmaTVDNSBl8lQR4gBWkmmRAdkcdFfOasLHD24wyUjmqgkOM2yTJ19Dw==
Certain characters must be escaped in url, and your verification token contains such characters, however you put it as is into your url here:
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={id}&verifyToken={confirmationToken}";
To escape them - use Uri.EscapeDataString:
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={Uri.EscapeDataString(id)}&verifyToken={Uri.EscapeDataString(confirmationToken)}";
We have an app that sends email to person(requestor) selected from a combobox. It only sends one email.
New requirement is that we want to send more than one email to more than one person.
The project owner does not want to replace the current combobox with a listbox. This will require additional database work.
So what was suggested to me for a solution is to add a listbox which is populated with the same information (name objects from the database) as the combobox.
The listbox will be used only when the user want to send email to extra people.
How do I modify the code for this button so that it sends email to the requestor selected in the combobox (which it is currently doing) and also send email to any requestor selected from the listbox?
Before the email is sent, I want to check to make sure that the selected requestor from the combobox is not also selected in the listbox. I do not want the requester to receive two email.
Here is the Listbox which has the same data for the requestor as the combobox.
public async void PopulateAdditionalStaffEmailListBox()
{
List<GetRequestorInfoModel> requestors = new List<GetRequestorInfoModel>();
try
{
requestors = await FTACaseReset.Controllers.RequestorInfoController.GetAllRequestorInfoes();
requestors = requestors.OrderBy(x => x.DisplayName).ToList(); //Has 15 items
//Populate AdditionalStaffEmailListBox
for (int i = 0; i < requestors.Count; i++)
{
ListBoxItem requestor = new ListBoxItem();
requestor.Text = requestors[i].DisplayName;
requestor.Value = requestors[i].RequestorInfoID;
AdditionalStaffEmailListBox.Items.Add(requestor.Text).ToString();
}
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "AdditionalStaffEmailListBox()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here is the code for the button that is currently sending email to requester selected from the combobox
private async void SendEmail(int selectedBatch)
{
string message = "The following records have been prepped for processing. Valid cases will be processed.{0}{1}{2}";
string requestorName = string.Empty;
string requestorEmail = string.Empty;
List<GetCandidateCaseModel> masterCandidateCasesListToDisplay = new List<GetCandidateCaseModel>();
try
{
masterCandidateCasesListToDisplay = await Controllers.CandidateCaseController.GetAllCandidates();
masterCandidateCasesListToDisplay = masterCandidateCasesListToDisplay.Where(x => x.BatchNumber == selectedBatch && x.RejectionReason != null).ToList();
if (masterCandidateCasesListToDisplay.Count > 0)
{
requestorName = masterCandidateCasesListToDisplay[0].RequestorInfo.DisplayName;
requestorEmail = masterCandidateCasesListToDisplay[0].RequestorInfo.Email;
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress("NoReply_FTA#courts.state.mn.us");
//Uncomment after testing June 2019
MailAddress to = new MailAddress(requestorEmail);
mailMessage.To.Add(to);
string ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
mailMessage.Subject = "FTA Case Reset Notice";
mailMessage.Body = message;
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMessage);
MessageBox.Show("An email has been sent to " + requestorName, "Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
MessageBox.Show("No Requestor was found. Unable to send an email.", "Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "SubmitButton_Click()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Its quite difficult understand your code if you dont show your custom classes.
The following code should work but be aware that comparing display names is not the best idea so if you can compare them by some id, do that instead.
private async void SendEmail(int selectedBatch)
{
string message = "The following records have been prepped for processing. Valid cases will be processed.{0}{1}{2}";
string requestorName = string.Empty;
string requestorEmail = string.Empty;
List<GetCandidateCaseModel> masterCandidateCasesListToDisplay = new List<GetCandidateCaseModel>();
try
{
masterCandidateCasesListToDisplay = await Controllers.CandidateCaseController.GetAllCandidates();
var selectedCandidate = masterCandidateCasesListToDisplay.Where(x => x.BatchNumber == selectedBatch && x.RejectionReason != null).ToList();
if (masterCandidateCasesListToDisplay.Count > 0)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
string requestorName0 = selectedCandidate[0].RequestorInfo.DisplayName;
string requestorEmail0 = selectedCandidate[0].RequestorInfo.Email;
MailMessage mailMessage = new MailMessage();
MailAddress to = new MailAddress(requestorEmail);
mailMessage.From = new MailAddress("NoReply_FTA#courts.state.mn.us");
mailMessage.To.Add(to);
mailMessage.Subject = "FTA Case Reset Notice";
mailMessage.Body = message;
mailMessage.IsBodyHtml = true;
string ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
foreach (ListViewItme item in AdditionalStaffEmailListBox.SelectedItems)
{
candidate = masterCandidateCasesListToDisplay.First(x => x.RequestorInfo.DisplayName == item.Value);
requestorName = candidate.RequestorInfo.DisplayName;
requestorEmail = candidate.RequestorInfo.Email;
if (requestorEmail0 == requestorEmail)
{
continue;
}
to = new MailAddress(requestorEmail);
mailMessage.To.Add(to);
ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
MessageBox.Show("An email has been sent to " + requestorName, "Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
smtpClient.Send(mailMessage);
}
else
{
MessageBox.Show("No Requestor was found. Unable to send an email.", "Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "SubmitButton_Click()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have a mail containing only a signature as an image and an attachment like the screenshot below.
I save this email as C:\mail.msg, I try then to read it by the code below:
var oApp = new Microsoft.Office.Interop.Outlook.Application();
MailItem outlookMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItemFromTemplate(#"C:\mail.msg");
//there are 2 attachments inside
foreach(var att in outlookMsg.Attachments)
{
att.SaveAsFile($#"C:\{att.FileName}");
}
The problem
There are 2 attachments inside the MailItem named :
-empty.xlsx
-lot4.xlsx
If I change the extension of lot4.xlsx to lot4.png, it can be opened as the image in the signature.
Someone has seen this strange situation when an attachment is added with name incorrect?
You could download attachments using the below code:
private void ThisApplication_NewMail()
{
Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
.Session.GetDefaultFolder(Outlook
.OlDefaultFolders.olFolderInbox);
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
inBoxItems = inBoxItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(#"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(#"Create Folder C:\TestFileSave");
}
}
}
For more information, please refer to this link:
How to: Programmatically save attachments from Outlook email items
With Microsoft EWS, its very easy to do:
reference: http://johnlabtest.blogspot.com/2014/01/save-attachments-from-exchange-mail-box.html
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("user1#contoso.com", RedirectionUrlValidationCallback);
var messages = new List<EmailMessage>();
// only get unread emails
SearchFilter folderSearchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// we just need the id in our results
var itemView = new ItemView(10) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
FindItemsResults<Item> findResults = service.FindItems(folder.Id, folderSearchFilter, itemView);
foreach (Item item in findResults.Items.Where(i => i is EmailMessage))
{
EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
messages.Add(message);
}
// loop through messages and call processemail here.
}
public static void ProcessEmail(EmailMessage message)
{
string saveDir = ConfigurationManager.AppSettings["AttachmentSaveDirectory"];
if (message.HasAttachments)
{
foreach (Attachment attachment in message.Attachments.Where(a=> a is FileAttachment))
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load(); // populate the content property of the attachment
using (FileStream fs = new FileStream(saveDir + attachment.Name, FileMode.Create))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
w.Write(fileAttachment.Content);
}
}
}
}
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve); // push changes back to server
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
I'm sending emails with asp.net core 2.0 like this
public string EmailServiceSend(string body, string subject = null, string to = null,
string multipleRecipients = null, string attachmentUrl = null, string smtpClient = null,
string userCredential = null, string userPassword = null, string from = null, bool template = false,
string templateRoute = null)
{
try
{
SmtpClient client = new SmtpClient("mysmtpserver");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("username", "password");
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("whoever#me.com");
mailMessage.To.Add("receiver#me.com");
mailMessage.Body = body;
mailMessage.Subject = subject;
client.Send(mailMessage);
}
catch(Exception ex)
{
ex.Message.ToString();
}
return "Email sended"
}
I want to know, how can I create a list of email domains to block and send an error message. For example I want to block this domains:
0-mail.com
0815.ru
0clickemail.com
0wnd.net
and then send a response into my return statement for example:
if(listofblockmails == true){
return "You can't add this email domain, change it please"
}
How can I achieve that? Regards
Try using Linq:
Lets say you have this List:
List<string> listofblockmails = new List<string>();
listofblockmails.Add("0-mail.com");
listofblockmails.Add("0815.ru");
listofblockmails.Add("0clickemail.com");
listofblockmails.Add("0wnd.net");
You can do as below:
if (listofblockmails.Contains("emailToBeChecked.com"))
{
//return "You can't add this email domain, change it please";
}
else
{
//send
//return "Email sended";
}
And let Garbage collector do the disposal.
You can simply parse the email address and get the domain part, and compare againist a list of bad domains. If the domain is present in your bad domain list, return messge.
You can create a method like this.
private bool IsGoodDomain(string email)
{
if (string.IsNullOrEmpty(email))
return false;
var badDomains = new List<string>
{
"0815.ru",
"0wnd.net"
};
var r = email.Split('#');
if (!r.Any()) return false;
var domainName = r.Last();
return !badDomains.Contains(domainName, StringComparer.InvariantCultureIgnoreCase);
}
and call this method in your other method
if(IsGoodDomain(someEmailAddressVariable))
{
//contnue sending
}
else
{
// return the error message
}
I'm very new to the ASP.NET C# area. I'm planning to send a mail through ASP.NET C# and this is the SMTP address from my ISP:
smtp-proxy.tm.net.my
Below is what I tried to do, but failed.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SendMail" %>
<html>
<head id="Head1" runat="server"><title>Email Test Page</title></head>
<body>
<form id="form1" runat="server">
Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
Message Body:<br>
<asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px" /><br>
<asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And below is my code-behind:
using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void Btn_SendMail_Click(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage(
txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}
PS: I'm sorry that I couldn't understand the receiver/sender SMTP concept, and so I am trying to understand the whole concept from here.
Just go through the below code.
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#MyWebsiteDomainName.com", "myIDPassword");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info#MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info#MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("MyEmailID#gmail.com"));
smtpClient.Send(mail);
Try using this code instead. Note: In the "from address" give your correct email id and password.
protected void btn_send_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add("to gmail address");
mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
mail.Subject = "This mail is send from asp.net application";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
}
}
You can try this using hotmail like this:-
MailMessage o = new MailMessage("From", "To","Subject", "Body");
NetworkCredential netCred= new NetworkCredential("Sender Email","Sender Password");
SmtpClient smtpobj= new SmtpClient("smtp.live.com", 587);
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);
Try the following :
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
string body = "Your registration has been done successfully. Thank you.";
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
message.Subject = "Thank You For Your Registration";
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = true;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
}
And then in you web.config add the following in between
<!--Email Config-->
<add key="FromEmailAddress" value="sender emailaddress"/>
<add key="FromEmailDisplayName" value="Display Name"/>
<add key="FromEmailPassword" value="sender Password"/>
<add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
<add key="SMTPPort" value="smptp Port"/>
You can try MailKit
MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. You can use easily in your application.You can download from here.
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(fromName, from#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Check this out .... it works
http://www.aspnettutorials.com/tutorials/email/email-aspnet2-csharp/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
emailClient.Send(message);
litStatus.Text = "Message Sent";
}
catch (Exception ex)
{
litStatus.Text=ex.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for RegexUtilities
/// </summary>
public class RegexUtilities
{
bool InValid = false;
public bool IsValidEmail(string strIn)
{
InValid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, #"(#)(.+)$", this.DomainMapper);
if (InValid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, #"^(?("")(""[^""]+?""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" + #"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
InValid = true;
}
return match.Groups[1].Value + domainName;
}
}
private void GetSendEmInfo()
{
#region For Get All Type Email Informations..!!
IPL.DoId = ddlName.SelectedValue;
DataTable dt = IdBL.GetEmailS(IPL);
if (dt.Rows.Count > 0)
{
hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
hidlink.Value = dt.Rows[0][link"].ToString();
}
#endregion
#region For Set Some Local Variables..!!
int StartLmt, FinalLmt, SendCurrentMail;
StartLmt = FinalLmt = SendCurrentMail = 0;
bool Valid_LimitMail;
Valid_LimitMail = true;
/**For Get Finalize Limit For Send Mail**/
FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
#region For Check Email Valid Limits..!!
if (FinalLmt > 0)
{
Valid_LimitMail = true;
}
else
{
Valid_LimitMail = false;
}
#endregion
/**For Get Finalize Limit For Send Mail**/
#endregion
if (Valid_LimitMail == true)
{
#region For Send Current Email Status..!!
bool EmaiValid;
string CreateFileName;
string retmailflg = null;
EmaiValid = false;
#endregion
#region For Set Start Limit And FinalLimit Send No Of Email..!!
mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
if (dtsendEmail.Rows.Count > 0)
{
StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
}
else
{
StartLmt = 0;
}
#endregion
#region For Find Grid View Controls..!!
for (int i = 0; i < GrdEm.Rows.Count; i++)
{
#region For Find Grid view Controls..!!
CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
lblCode.Value = lbl_InNo.Text;
Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");
#endregion
/**Region For If Check Box Checked Then**/
if (Chk_SelectOne.Checked == true)
{
if (!string.IsNullOrEmpty(lbl_EmailId.Text))
{
#region For When Check Box Checked..!!
/**If Start Limit Less Or Equal To Then Condition Performs**/
if (StartLmt < FinalLmt)
{
StartLmt = StartLmt + 1;
}
else
{
Valid_LimitMail = false;
EmaiValid = false;
}
/**End Region**/
string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
string Send_Email, Hold_Email;
Send_Email = Hold_Email = "";
int CountEmail;/**Region For Count Total Email**/
CountEmail = 0;/**First Time Email Counts Zero**/
Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
/**Region For If Clients Have One Email**/
#region For First Emails Send On Client..!!
if (SplitClients_Email[0].ToString() != "")
{
if (EmailRegex.IsValidEmail(Hold_Email))
{
Send_Email = Hold_Email;
CountEmail = 1;
EmaiValid = true;
}
else
{
EmaiValid = false;
}
}
#endregion
/**Region For If Clients Have One Email**/
/**Region For If Clients Have Two Email**/
/**Region For If Clients Have Two Email**/
if (EmaiValid == true)
{
#region For Create Email Body And Create File Name..!!
//fofile = Server.MapPath("PDFs");
fofile = Server.MapPath("~/vvv/vvvv/") + "/";
CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
string[] orimail = Send_Email.Split(',');
string Billbody, TempInvoiceId;
// DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);
// DateTime IndtLmt = dtLstdate.AddMonths(1);
TempInvoiceId = "";
//byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
//TempInvoiceId = Convert.ToBase64String(Buffer);
#region Create Encrypted Path
byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
#endregion
//#region Create Email Body !!
//body = hid_EmailBody.Value.Replace("#greeting", lbl_CoName.Text).Replace("#free", hid_ToNo.Value).Replace("#llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
body = hid_EmailBody.Value.Replace("#greeting", "Hii").Replace("#No", hid_No.Value);/*For Mail*/
//#endregion
#region For Email Sender Informations..!!
for (int j = 0; j < CountEmail; j++)
{
//if (File.Exists(fofile + "\\" + CreateFileName))
//{
#region
lbl_EmailId.Text = orimail[j];
retmailflg = "";
/**Region For Send Email For Clients**/
//retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
/**End Region**/
/**Region For Create Send Email Log When Email Send Successfully**/
if (retmailflg == "True")
{
SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
StartLmt = Convert.ToInt32(StartLmt) + 1;
if (SendCurrentMail > 0)
{
CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
}
}
/**End Region**/
#endregion
//}
}
#endregion
}
#endregion
}
}
/**End Region**/
}
#endregion
}
}
private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
{
FPL.EmailId_From = FromEmailId;
FPL.To_EmailId = TotxtEmailId;
FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
FPL.EmailUniqueId = UniqueId;
FPL.SendNo_Of_Email = StartLmt.ToString();
FPL.LoginUserId = Session["LoginUserId"].ToString();
int i = FBL.InsertEmaDoc(FPL);
}
public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
{
string retval = "False";
try
{
string emailBody, emailSubject, emailToList, emailFrom,
accountPassword, smtpServer;
bool enableSSL;
int port;
emailBody = embody;
emailSubject = emsub;
emailToList = EmailId;
emailFrom = EmailFromId;
accountPassword = Password;
smtpServer = "smtp.gmail.com";
enableSSL = true;
port = 587;
string crefilename;
string fofile;
fofile = Server.MapPath("PDF");
crefilename = FileId + ".Pdf";
string[] att = { crefilename };
string retemail, insertqry;
retemail = "";
retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);
if (retemail == "True")
{
retval = retemail;
}
}
catch
{
retval = "False";
}
finally
{
}
return retval;
}
public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
{
MailMessage mail = new MailMessage();
string retflg;
retflg = "False";
try
{
mail.From = new MailAddress(emailFrom);
if (emailToList.Contains(";"))
{
emailToList = emailToList.Replace(";", ",");
}
mail.To.Add(emailToList);
mail.Subject = emailSubject;
mail.IsBodyHtml = true;
mail.Body = emailBody;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mail);
retflg = "True";
}
catch
{
retflg = "False";
}
finally
{
mail.Dispose();
}
return retflg;
}
Just pass parameter
like
body - The content(query) from the customer
subject - subject that defined in mail subject
username - nothing name anything
mail - mail (required)
public static bool SendMail(String body, String subject, string username, String mail)
{
bool isSendSuccess = false;
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
new MailAddress(mail, username));
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = false;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
isSendSuccess = true;
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
}
return isSendSuccess;
}
if your using go daddy server this work . add this in web.config
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="myemail#gmail.com" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword#" />
<add key="SMTPHost" value="relay-hosting.secureserver.net" />
<add key="SMTPPort" value="25" />
</appSettings>
if you are using localhost or vps server change this configuration to this
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="myemail#gmail.com" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword#" />
<add key="SMTPHost" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
</appSettings>
change the code
client.EnableSsl = true;
if your are using gmail please enable secure app. using this link
https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA
If you want to generate your email bodies in razor, you can use Mailzory. Also, you can download the nuget package from here.
// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);
var email = new Email(template);
// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";
// send email
var task = email.SendAsync("mailzory#outlook.com", "subject");
task.Wait()
According to this :
SmtpClient and its network of types are poorly designed, we strongly
recommend you use https://github.com/jstedfast/MailKit and
https://github.com/jstedfast/MimeKit instead.
Reference : https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8
It's better to use MailKit to send emails :
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler#friends.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart ("plain") {
Text = #"Hey Chandler,
I just wanted to let you know that Monica and I were going to go play some paintball, you in?
-- Joey"
};
using (var client = new SmtpClient ()) {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect ("smtp.friends.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate ("joey", "password");
client.Send (message);
client.Disconnect (true);
}
Google may block sign-in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.
Some examples of apps that do not support the latest security standards include:
The Mail app on your iPhone or iPad with iOS 6 or below
The Mail app on your Windows phone preceding the 8.1 release
Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird
Therefore, you have to enable Less Secure Sign-In (or Less secure app access) in your google account.
After sign into a google account, go to:
https://www.google.com/settings/security/lesssecureapps
or
https://myaccount.google.com/lesssecureapps
In C#, you can use the following code:
MimeMessage message = new MimeMessage();
BodyBuilder Attachmint = new BodyBuilder();
message.From.Add(new MailboxAddress("name sender", "Mail From"));
message.To.Add(MailboxAddress.Parse("Mail To"));
message.Subject = Subject;
message.Body = new TextPart("plain")
{
Text = tex_body.Text + Massage
};
Attachmint.Attachments.Add("Attatchment Path");
message.Body = Attachmint.ToMessageBody();
SmtpClient client = new SmtpClient();
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("Mail from", "Password mail");
client.Send(message);
you can send mail from Gmail to Private Mail As X#PrivetCompany.com
Answer Update 2023
C# code for Email (GMAIL) Service
using System;
using System.Net;
using System.Net.Mail;
namespace EmailApp
{
internal class Program
{
public static void Main(string[] args)
{
String SendMailFrom = "Sender Email";
String SendMailTo = "Reciever Email";
String SendMailSubject = "Email Subject";
String SendMailBody = "Email Body";
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage email = new MailMessage();
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.CC.Add(SendMailFrom);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Timeout = 5000;
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
SmtpServer.Send(email);
Console.WriteLine("Email Successfully Sent");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
For further help, you can refer to: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
View Video: https://www.youtube.com/watch?v=bUUNv-19QAI
This is the easiest script to test.
<%# Import Namespace="System.Net" %>
<%# Import Namespace="System.Net.Mail" %>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("From email account");
mail.To.Add("To email account");
//set the content
mail.Subject = "This is a test email from C# script";
mail.Body = "This is a test email from C# script";
//send the message
SmtpClient smtp = new SmtpClient("mail.domainname.com");
NetworkCredential Credentials = new NetworkCredential("to email account", "Password");
smtp.Credentials = Credentials;
smtp.Send(mail);
lblMessage.Text = "Mail Sent";
}
</script>
<html>
<body>
<form runat="server">
<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>