This is my code try to send mailif you have any idea to solve this help me guys
enter code here
public ActionResult ContactForm(Contact cnt)
{
BlogApplicationEntities db = new BlogApplicationEntities();
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
msg.To.Add(new MailAddress("send to mail address"));
msg.Subject = "Contact Us";
msg.Body += "\nFirst Name=" + cnt.FirstName;
msg.Body += "Last Name=" + cnt.LastName;
msg.Body += "Email=" + cnt.Email;
msg.From = new MailAddress("mailaddress", "Jhon");
msg.Body += "Comments=" + cnt.Comment;
msg.IsBodyHtml = true;
smtp.Credentials = new System.Net.NetworkCredential("network mail address", "**password**");
smtp.Host = "https://smtp.gmail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Port = 587;
smtp.Send(msg);
msg.Dispose();
db.Contacts.Add(cnt);
db.SaveChanges();
return View("Success");
}
catch (Exception)
{
return View("Error");
}
}
return View();
}
When the below line is executed:
smtp.Send(msg);
Its throws an error :
'The remote name couldn't be resolved: https://smtp.gmail.com'
What can I do to solve this, can someone help me?
Change https://smtp.gmail.com, to smtp.gmail.com, and you need to validate a proper gmail account. Follow examples showed in this post.
You need to change your SMTP host to smtp.gmail.com:
public ActionResult ContactForm(Contact cnt)
{
BlogApplicationEntities db = new BlogApplicationEntities();
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
msg.To.Add(new MailAddress("ibrahimtirampaci#hotmail.com"));
msg.Subject = "Contact Us";
msg.Body += "\nFirst Name=" + cnt.FirstName;
msg.Body += "Last Name=" + cnt.LastName;
msg.Body += "Email=" + cnt.Email;
msg.From = new MailAddress("ibrahimtirampaci#hotmail.com", "İbrahim");
msg.Body += "Comments=" + cnt.Comment;
msg.IsBodyHtml = true;
smtp.Credentials = new System.Net.NetworkCredential("ibrahimtirampaci#hotmail.com", "2117542ibo");
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Port = 587;
smtp.Send(msg);
msg.Dispose();
db.Contacts.Add(cnt);
db.SaveChanges();
return View("Success");
}
catch (Exception)
{
return View("Error");
}
}
return View();
}
Host names don't include the transport protocol, but when you specify EnableSsl=true, you're setting the transport protocol to SSL. One side note, make sure that you're using a gmail account for your network credentials if you're sending from gmail.
I changed the smtp to smtp.Host = "smtp.gmail.com" but now Its throws an error : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
I think my problem is null Credentials.
Related
Triggering mail from ASP.net Core MVC application, using Exchange.WebServices.Managed.Net5(https://www.nuget.org/packages/Exchange.WebServices.Managed.Net5/2.2.0).Intermittently getting the System.NullReferenceException: Object reference not set to an instance of an object., Sometimes mail gets send even after the exception.
Why this error and how can it be solve?
public static void CreateMessage(string username, string To, string Subject, string Msg, string Smtp, int Port, string Password, bool useSsl, string ToCc = "")
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Url = new Uri("https://" + Smtp + "/ews/Exchange.asmx");
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
service.UseDefaultCredentials = false;
service.Credentials = new WebCredentials(username, Password);
EmailMessage message = new EmailMessage(service);
message.Subject = Subject;
message.Body = Msg;
message.ToRecipients.Add(To);
if (!string.IsNullOrEmpty(ToCc))
message.CcRecipients.Add(ToCc);
message.Save();
message.SendAndSaveCopy();
}
catch (Exception ex)
{
throw new Exception("Email sending error:" + ex.ToString());
}
}
I have the code below
MimeMessage message = new MimeMessage();
MailboxAddress from = new MailboxAddress("Admin",
"myemail#gmail.com");
message.From.Add(from);
MailboxAddress to = new MailboxAddress("User",
"myemail2#gmail.com");
message.To.Add(to);
message.Subject = "Hi user";
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = "message body here";
message.Body = bodyBuilder.ToMessageBody();
SmtpClient client = new SmtpClient();
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("myemail#gmail.com", "pass");
client.Send(message);
client.Disconnect(true);
client.Dispose();
It says my credentials are not correct even though they are. I'm using MailKit and MimeMessage.
What am I doing wrong here?
try to use port 587 instead of 465.
Here's the link to my github repository, a simple project to send mails.
https://github.com/osman-developer/sendingMails
You can use something like that.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test Project",
"your email"));
message.To.Add(new MailboxAddress("pritom", email));
message.Subject = "Hi,this is demo email";
message.Body = new TextPart("plain")
{
Text = "Hello,My First Demo Mail it is.Thanks",
};
//add attach
MemoryStream memoryStream = new MemoryStream();
BodyBuilder bb = new BodyBuilder();
using (var wc = new WebClient())
{
//bb.Attachments.Add("attachmentName",
wc.DownloadData("wwwroot/Images/H.pdf"));
bb.Attachments.Add("Email.pdf",
wc.DownloadData("wwwroot/Images/Email.pdf"));
//bb.Attachments.Add("H.pdf", new MemoryStream());
}
message.Body = bb.ToMessageBody();
//end attach
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("your email",
"yourpassword");
client.Send(message);
client.Disconnect(true);
}
Update
go to this link
enter link description here
and allow a less secure app.
If you are facing the same issue, go on your gmail account > security > allow less secure apps. This solved my problem
I am storing the email of the user in session
var v = //login query
Session["LoggedUserEmail"] = v.email.ToString();
Then after login I want to send an email to the current logged in user and for that purpose I am passing Session["LoggedUserEmail"] in Msg.To.Add but its not working.
This is what I am doing
public void Execute(IJobExecutionContext context)
{
System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
Msg.From = new MailAddress("abc#gmail.com");
Msg.To.Add(Session["LoggedUserEmail"].ToString());
Msg.Subject = "Email";
Msg.Body = "Hi";
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("abc#gmail.com", "xxxxxxx");
smtp.EnableSsl = true;
smtp.Send(Msg);
Response.Write("Email Sent");
}
Am I doing something wrong? if yes, then is there any other way to get the job done?
I am using quartz.net and implemented IJob interface in my mvc controller.
The job executes on a different thread than the one that schedules it. You must pass in any data you need by using the JobDataMap when creating/scheduling the job.
I have tried
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
but sign is not replaced the space provided in pdf. Can you please provide a code sample for using the Soap API.
Please see the code sample below for using CoSign Signature SOAP API (aka SAPIWS) with CoSign Signature Locators:
public SAPISigFieldSettingsType[] getSigFieldLocatorsInPDF(
string FileName,
string UserName,
string Password)
{
//Create Request object contains signature parameters
RequestBaseType Req = new RequestBaseType();
Req.OptionalInputs = new RequestBaseTypeOptionalInputs();
//Here Operation Type is set: enum-field-locators
Req.OptionalInputs.SignatureType = SignatureTypeFieldLocators;
//Configure Create and Sign operation parameters:
Req.OptionalInputs.ClaimedIdentity = new ClaimedIdentity();
Req.OptionalInputs.ClaimedIdentity.Name = new NameIdentifierType();
Req.OptionalInputs.ClaimedIdentity.Name.Value = UserName; //User Name
Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier = " "; //Domain (relevant for Active Directory environment only)
Req.OptionalInputs.ClaimedIdentity.SupportingInfo = new CoSignAuthDataType();
Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password; //User Password
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
//Set Session ID
Req.RequestID = Guid.NewGuid().ToString();
//Prepare the Data to be signed
DocumentType doc1 = new DocumentType();
DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();
Req.InputDocuments = new RequestBaseTypeInputDocuments();
Req.InputDocuments.Items = new object[1];
b64data.MimeType = "application/pdf"; //Can also be: application/msword, image/tiff, pplication/octet-string
Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = false;
b64data.Value = ReadFile(FileName, true); //Read the file to the Bytes Array
doc1.Item = b64data;
Req.InputDocuments.Items[0] = doc1;
//Call sign service
ResponseBaseType Resp = null;
try
{
// Create the Web Service client object
DSS service = new DSS();
service.Url = "https://prime.cosigntrial.com:8080/sapiws/dss.asmx"; //This url is constant and shouldn't be changed
SignRequest sreq = new SignRequest();
sreq.InputDocuments = Req.InputDocuments;
sreq.OptionalInputs = Req.OptionalInputs;
//Perform Signature operation
Resp = service.DssSign(sreq);
if (Resp.Result.ResultMajor != Success )
{
MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
Resp.Result.ResultMinor + " " +
Resp.Result.ResultMessage.Value, "Error");
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
if (webResponse != null)
MessageBox.Show(we.Response.ToString(), "Web Response");
}
return null;
}
//Handle Reply
DssSignResult sResp = (DssSignResult) Resp;
return Resp.OptionalOutputs.SAPISeveralSigFieldSettings;
}
I am trying to send send email through below action method
[HttpPost]
public ActionResult ForgotPassword1()
{
dbAlKhaleejEntities _context = new dbAlKhaleejEntities();
var email = Request["Email"];
var email_adress = _context.CUSTOMERs.First(em => email == em.CUSTOMER_EMAIL);
var mailto = email_adress.CUSTOMER_EMAIL;
MailMessage msg = new MailMessage();
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Credentials = new NetworkCredential("umairliaquat63#gmail.com", "abc");
client.Host = "smtp.gmail.com";
client.Port = 587;
msg.From = new MailAddress("umairliaquat63#gmail.com");
msg.To.Add(mailto);
msg.Subject = "Password recovery";
msg.Body = "Test Recovering the password";
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Send(msg);
return RedirectToAction("forgetPassword");
}
but at line "client.Send(msg)" , it is throwing exception "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required". How I should solve this problem
As far as I know you don't need write your own code cause SmtpClient can use your configuration:
<system.net>
<mailSettings>
<smtp from="It's me <its#my.email>">
<network host="smtp.ip.or.domain" port="527" defaultCredentials="false" userName="noreply" password="12345" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
Verify your mail settings twice. In addition, the SMTP server can reject connections for IP's from a black list, or not from a white list. The SMTP server can detect your mail as a spam.
You can use your own local SMTP or specialized servises to mass mailings.
Try this snippet :
using (var client = new SmtpClient(SmtpServerHost, SmtpPort)
{
Credentials = new NetworkCredential(NetworkCredentialUserName, Password),
EnableSsl = this.enableSSL
}
)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromMailingAddress);
msg.Subject = this.Subject;
}