I have C# code for sending Email (in Controller), that is working fine, Email gets shoot with no Problem
public ActionResult SendEmail(string msg, int formNum)
{
var sent = false;
try
{
var emailClient = new EmailServiceReference.EmailServiceClient();
sent = emailClient.SendEmail(fromEmail, toEmail, emailsubject+""+ formNum, msg);
// from and to values are defined.
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}
As you can see there are two parameters for SendEmail() method "msg" & "formNum". I am using those parameters to send the email as Subject(formNum) and Body(msg).
Now, I have 8- 10 parameters getting in SendEmail(FirstName, LastName, ID, Age, PhoneNumber, etc) Method and those I want to use in Email Body. The task for me is to create HTML table in Email body with all details and email it to XYZ#xyz.com
I need help to construct data in HTML table with data in Controller and how can I send it as argument (msg) in method call.?
Thank You
I have modified your code. See if this works.
using System.Net.Mail;
//...
public ActionResult SendEmail(string msg, int formNum)
{
var sent = false;
try
{
var emailClient = new SmtpClient();
var mailMessage = new MailMessage(fromEmail, toEmail);
mailMessage.Subject = emailsubject +" " + formNum;
mailMessage.Body = msg;
mailMessage.IsBodyHtml = true;
emailClient.Send(mailMessage);
sent = true;
// from and to values are defined.
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}
Related
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)}";
I am trying to send e-mail from within a Xamarin Forms app, using Gmail.
I have created an Interface with only 1 method: SendEmail();
Then, in the Droid project, I added a class which implements said interface. Using the Dependency attribute and getting the implementation of the method in the main project, all is fine, except the following error:
Could not resolve host 'smtp.gmail.com'
This is the actual implementation of the method:
string subject = "subject here ";
string body= "body here ";
try
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("myEmailAddress#gmail.com");
mail.To.Add("anotherAddress#yahoo.com");
mail.Subject = subject;
mail.Body = body;
smtpServer.Credentials = new NetworkCredential("username", "pass");
smtpServer.UseDefaultCredentials = false;
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
Searching around I could not find any details regarding it other that the actual smtp address.
Also, I have used the Less Secure apps procedure from Google, not receiving a credentials error I assume that it can connect to the account just fine.
Hello I have achieve this using the code below, also I have attached a file to the email, using the dependency service I use this methods:
Android:
public static string ICSPath
{
get
{
var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
Intent choserIntent = new Intent(Intent.ActionSend);
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
Java.IO.File filelocation = new Java.IO.File(ICSPath);
var path = Android.Net.Uri.FromFile(filelocation);
// set the type to 'email'
choserIntent.SetType("vnd.android.cursor.dir/email");
//String to[] = { "asd#gmail.com" };
//emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
choserIntent.PutExtra(Intent.ExtraStream, path);
// the mail subject
choserIntent.PutExtra(Intent.ExtraSubject, "Calendar event");
Forms.Context.StartActivity(Intent.CreateChooser(choserIntent, "Send Email"));
return true;
}
iOS:
public static string ICSPath
{
get
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
MFMailComposeViewController mail;
if (MFMailComposeViewController.CanSendMail)
{
mail = new MFMailComposeViewController();
mail.SetSubject("Calendar Event");
//mail.SetMessageBody("this is a test", false);
NSData t_dat = NSData.FromFile(ICSPath);
string t_fname = Path.GetFileName(ICSPath);
mail.AddAttachmentData(t_dat, #"text/v-calendar", t_fname);
mail.Finished += (object s, MFComposeResultEventArgs args) =>
{
//Handle action once the email has been sent.
args.Controller.DismissViewController(true, null);
};
Device.BeginInvokeOnMainThread(() =>
{
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mail, true, null);
});
}
else
{
//Handle not being able to send email
await App.BasePageReference.DisplayAlert("Mail not supported",
StaticData.ServiceUnavailble, StaticData.OK);
}
return true;
}
I hope this helps.
Figured it own finally!
First of all, I was using Android Player by Xamarin, which apparently does not support network connectivity.
So my fix was easy: used an Android Emulator ( any version of it for that matter ) built in Visual Studio Community 2015, and tested network connectivity using the plugin by James Montemagno ( Xam.Plugin.Connectivity on NuGet ).
I have a SSIS package where I have created a Script task on the OnError event to send an email alerting users to the fact that an error has occurred.
This works fine but what I would like to do is include in my email body the exception message that caused the event handler to fire. How can I get access to the exception inside the script task?
Current script body:
/// <summary>
/// This method is called when this script task executes in the control flow.
/// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
/// To open Help, press F1.
/// </summary>
public void Main()
{
try
{
string mailBody = "<p>XXXX package has failed.</p><p>Please investigate.</p>";
string mailFrom = Dts.Variables["MailFrom"].Value.ToString();
string errorMailTo = Dts.Variables["ErrorMailTo"].Value.ToString();
string smtpConnectionString = (string)(Dts.Connections["SMTPConnectionManager"].AcquireConnection(Dts.Transaction));
string smtpServer = smtpConnectionString.Split(new char[] { '=', ';' })[1];
var smtpClient = new SmtpClient(smtpServer);
var message = new MailMessage(mailFrom, errorMailTo, mailSubject, mailBody) { IsBodyHtml = true };
// TODO append exception message to the mail body.
smtpClient.Send(message);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
string message = ex.Message;
if (ex.InnerException != null)
{
message = message + " " + ex.InnerException.Message;
}
Dts.Log("Error email sending failure - " + message, 0, new byte[0]);
Dts.TaskResult = (int)ScriptResults.Failure;
throw;
}
}
This is typically stored in the #[System::ErrorDescription] variable, which you will need to map as read only to access.
You can also use #[System::ErrorCode], but SSIS error codes are generally not very helpful.
Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}
After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);
I am sorry if this has been posted before. I have searched many websites and forms to fix it but I can not get it. I have a simple contact form that allows potential customers to fill out their info click submit and then email a copy of what they inputted to us. I have the email part working fine. However, the part that's not working is message after the form is submitted. I'm try to use a try and catch to display a message when they submit or a err message when it didn't work. Not sure why it is not working. Thank you for the help. My controller code is below.
public ActionResult ContactForm()
{
return View();
}
public ActionResult Message()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactForm(ContactModel emailModel)
{
if (ModelState.IsValid)
{
bool isOk = false;
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("no-reply#bobcravens.com", "Website Contact Form");
msg.To.Add("thovden#hovdenoil.com");
msg.Subject = emailModel.Subject;
string body = "Name: " + emailModel.Name + "\n"
+ "Email: " + emailModel.Email + "\n"
+ "Website: " + emailModel.Website + "\n"
+ "Phone: " + emailModel.Phone + "\n\n"
+ emailModel.Message;
msg.Body = body;
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtpout.server.net", 25);
NetworkCredential Credentials = new NetworkCredential("thovden#hovdenoil.com", "****");
smtp.Credentials = Credentials;
smtp.Send(msg);
msg.Dispose();
isOk = true
ContactModel rcpt = new ContactModel();
rcpt.Title = "Thank You";
rcpt.Content = "Your email has been sent.";
return View("Message", rcpt);
}
catch (Exception ex)
{
}
// If we are here...something kicked us into the exception.
//
ContactModel err = new ContactModel();
err.Title = "Email Error";
err.Content = "The website is having an issue with sending email at this time. Sorry for the inconvenience. My email address is provided on the about page.";
return View("Message", err);
}
else
{
return View();
}
}
}
The problem is that view that you return:
return View("Messgae", err):
You should return the same view after error on "postback", with the invalid model
return View(err);
One time you call that Message view with MessageModel and in this line you called it with ContactModel, so there must be an error over here...
Side notes:
You're catching the Global Exception exception it isn't good practice. Not every exception you can and should handle.
You have an isOK flag that doesn't do a thing.
Move the exception Handel inside the catch block, not afterwards
Updated based on the comments:
Instead of return View you should Redirect:
return RedirectToAction("Message", err);
return RedirectToAction("Message", rcpt);
public ActionResult Message(ContactModel model)
{
return View(model);
}
I would start by emitting the exception so that you can figure out exactly what went wrong. Additionally, you might want to step through the code.