Send Email from an Asp.Net Webform Application using Microsoft Outlook - c#

I have anasp.net web form which on click of a button sends i want an email to be sent to my Microsoft outlook email account. I have done this on other
websites but that was using hotmail but all external web email providers are blocked by the companies firewall (as i tried setting up a gmail account) so
i need to use Outlook but i have not idea on how to implent this and solutions i have seen on Google dont seem to work. I dont know if it'll make a
difference or not but i have been informed that the users password epxires every 30days so i suspect i'll need to use windows authenication or something
but not sure.
I'm not sure on how Outlook send the email as i know from past experience from using hotmail that the email is just sent on click of the button but i'm
not sure if outlook would open the email window for the user to click the send button. If it does, i need the information captured on the webform to be
containd in the email and the content of the email body not to be altered (if this can be done, again not ot sure if it can but not a problem if it
can't).
Below is the code i used for when i tried gmail but as i said i was told it wouldnt be allowed.
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
#region Email
try
{
//Creates the email object to be sent
MailMessage msg = new MailMessage();
//Adds your email address to the recipients
msg.To.Add("MyEmailAddress#Test.co.uk");
//Configures the address you are sending the email from
MailAddress address = new MailAddress("EmailAddress#Test.com");
msg.From = address;
//Allows HTML to be used when setting up the email body
msg.IsBodyHtml = true;
//Email subjects title
msg.Subject = "Place Suggestion";
msg.Body = "<b>" + lblPlace.Text + "</b>" + " " + fldPlace.Text
+ Environment.NewLine.ToString() +
"<b>" + lblLocation.Text + "</b>" + " " + fldLocation.Text
+ Environment.NewLine.ToString() +
"<b>" + lblName.Text + "</b>" + " " + fldName.Text;
//Configures the SmtpClient to send the mail
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true; //only enable this if the provider requires it
//Setup credentials to login to the sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("MyEmailAddress#Test.co.uk", "MyPassword");
client.Credentials = credentials;
//Send the email
client.Send(msg);
}
catch
{
//Lets the user know if the email has failed
lblNotSent.Text = "<div class=\"row\">" + "<div class=\"col-sm-12\">" + "There was a problem sending your suggestion. Please try again."
+ "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-sm-12\">" + "If the error persists, please contact Antony." + "</div>" +
"</div>";
}
#endregion
}

edit 2: Now we have established your going through exchance this is how my code has always worked
SmtpClient sptmClient = new SmtpClient("exchange server name")
MailMessage m = new MailMessage();
m.To.Add(new MailAddress("Address"));
m.From = new MailAddress("");
m.Subject = "";
m.Body = "";
m.IsBodyHtml = true;
sptmClient.Send(m);
but there is another answer on here that uses outlook interoperlation that might work better for you

With Exchange it must work.
test this :
using Outlook = Microsoft.Office.Interop.Outlook;
private void SendWithExchange()
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem mail = oApp.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Exemple à tester";
Outlook.AddressEntry currentUser =
oApp.Session.CurrentUser.AddressEntry;
if (currentUser.Type == "EX")
{
Outlook.ExchangeUser manager =
currentUser.GetExchangeUser();
mail.Recipients.Add(manager.PrimarySmtpAddress);
mail.Recipients.ResolveAll();
//mail.Attachments.Add(#"c:\sales reports\fy06q4.xlsx",
// Outlook.OlAttachmentType.olByValue, Type.Missing,
// Type.Missing);
mail.Send();
}
}

Related

I can send smtp message on a localHost But i cant send it on a Live WebSite

im using Asp.net And I have the Umbraco Cms on my project
i implemented The Send message using razor syntax
im submitting a from to the following razor syntax
#{ if (IsPost)
{
string name = Request["name"];
string email = Request["email"];
string phone = Request["phone"];
string city = Request["city"];
string note = Request["note"];
NetworkCredential basicCredential =new NetworkCredential("*****#gmail.com", "******");
MailMessage mail = new MailMessage();
//var from = new MailAddress(Email.Text);
mail.From = new MailAddress(email);
mail.To.Add("tupacmuhammad5#gmail.com");
mail.Subject = "Torcan WebSite Contact Us";
mail.IsBodyHtml = false;
mail.Body = "You just got a contact email:\n" +
"Name: " + name + "\n"
+ "Email: " + email + "\n"
+ "TelePhone: " + phone + "\n"
+ "Address: " + city + "\n"
+ "Message: " + note + "\n";
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = basicCredential;
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
finally
{
smtp.Dispose();
}
}
}
it works perfect on My localHost But on a live server its thorws a runtime error "after i remove the try catch "
i cant find out what seems to be problem
im writing this code in umbraco backoffice tamplate i have the server on onther country and i dont have access to it any help ? please ?
The Problem was that the Server is located in Germany so when the server tries to open my Gmail account. its a different country and never seen action from there.
so all i had to do is to open my gmail via remote access on the server machine via a browser and confirmed it was me then every thing worked perfectly.

Getting "The specified string is not in the form required for an e-mail address." errror

string email = "select seller.emailid from seller inner join cars on seller.sid=cars.sid where cars.carid='" + lbllid + "' ";
GridView1.EditIndex = -1;
MailMessage MyMailMessage = new MailMessage("****#gmail.com", email, "Ruby Cabs Email Confirmation", Environment.NewLine + " This is an email automated sevice." + Environment.NewLine + "Your car has been approved. Thank you for taking out time to fill the data." + Environment.NewLine + "Regards," + Environment.NewLine + "Ruby Cabs");
MyMailMessage.IsBodyHtml = false;
NetworkCredential mailAuthentication = new NetworkCredential("****#gmail.com", "****");
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
I have checked the query on sql server and it works fine. Can any one tell whats the issue
You're putting a SQL query in the email field when calling new MailMessage(...).
You'll need to run the query against your SQL server, get the result set, extract the email address from said result set, and use THAT as your email address.
The debugger is your friend.

Hooking into SMTP client events

Intro: I am supporting a piece of code that sends a welcome/confirm mail upon successful registration to a site.
The SMTP client times out before sending can complete. According to our Ops department, I am using the correct credentials and SMTP server IP address.
What I want to do is hook into any handshaking, connection, sending, etc events so that I can figure out exactly why the process times out. I've set Server.ScriptTimeOut to 500 seconds on that page, so it can't just be a busy server problem.
My question is this: what events can I handle during this process. The only one I see exposed in SMTPClient is SendCompleted. But I imagine there must be a way to get access to something more low-level?
For reference, here's the code:
//Create and send email
MailMessage mm = new MailMessage();
try
{
mm.From = new MailAddress("admin#site.com");
mm.To.Add(new MailAddress(Recipient));
mm.Subject = Subject;
mm.Body = MailBody;
mm.IsBodyHtml = true;
var c = new NetworkCredential("admin#site.com", "YeOlePassword");
SmtpClient smtp = new SmtpClient("127.0.0.1");//not really, just hiding our SMTP IP from StackOverflow
smtp.UseDefaultCredentials = false;
smtp.Credentials = c;
smtp.Send(mm);
}
catch (Exception x)
{
DateTime CurrentDateTime = DateTime.Now;
String appDateTime = CurrentDateTime.ToString();
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + x.Message;
StreamWriter streamwriter = new StreamWriter(File.Open(MapPath("~/TransactionLog.txt"), FileMode.Append, FileAccess.Write, FileShare.Write));
//Append to file
streamwriter.WriteLine(transactionLogEntry);
//Close file
streamwriter.Close();
}
The error that's logged is simply that a timeout occured while sending a mail to the supplied email address.
I use this to get the buried SMTP messages out.
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + GetFullErrorMessage(x);
.
.
.
private string GetFullErrorMessage(Exception e)
{
string strErrorMessage = "";
Exception excpCurrentException = e;
while (excpCurrentException != null)
{
strErrorMessage += "\"" + excpCurrentException.Message + "\"";
excpCurrentException = excpCurrentException.InnerException;
if (excpCurrentException != null)
{
strErrorMessage += "->";
}
}
strErrorMessage = strErrorMessage.Replace("\n", "");
return strErrorMessage;
}
In my experience, from what you are describing it is related to your SMTP port being blocked by and ISP or your server/web host. Good luck!

send email asp.net c#

Is it possible to send email from my computer(localhost) using asp.net project in C#?
Finally I am going to upload my project into webserver but I want to test it before uploading.
I've found ready source codes and tried run them in localhost, but neither of them work succesfully.
For example this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
namespace sendEmail
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
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("localhost");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}
}
So how to send email using asp.net C#? Should I setup some server configurations?
Sending Email from Asp.Net:
MailMessage objMail = new MailMessage("Sending From", "Sending To","Email Subject", "Email Body");
NetworkCredential objNC = new NetworkCredential("Sender Email","Sender Password");
SmtpClient objsmtp = new SmtpClient("smtp.live.com", 587); // for hotmail
objsmtp.EnableSsl = true;
objsmtp.Credentials = objNC;
objsmtp.Send(objMail);
if you have a gmail account you can use google smtp to send an email
smtpClient.UseDefaultCredentials = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(username,passwordd);
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
Your code above should work fine, but you need to add the following to your web.config (as an alternative to any code-based SMTP configuration):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="your.smtpserver.com" port="25" userName="smtpusername" password="smtppassword" />
</smtp>
</mailSettings>
</system.net>
If you don't have access to a remote SMTP server (I use my own POP3 / SMTP email details), you can set up an SMTP server in your local IIS instance, but you may run in to issues with relaying (as most ISP consumer IP addresses are black listed).
A good alternative, if you don't have access to an SMTP server, is to use the following settings instead of the above:
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\mail"/>
</smtp>
</mailSettings>
</system.net>
This will create a hard disk copy of the email, which is pretty handy. You will need to create the directory you specify above, otherwise you will receive an error when trying to send email.
You can configure these details in code as per other answers here (by configuring the properties on the SmtpClient object you have created), but unless you're getting the information from a data source, or the information is dynamic, it's superfluous coding, when .Net already does this for you.
You can send email from ASP.NET via C# class libraries found in the System.Net.Mail namespace. take a look at the SmtpClient class which is the main class involved when sending emails.
You can find code examples in Scott Gu's Blog or on the MSDN page of SmtpClient.
Additionally you'll need an SMTP server running. I can recommend to use SMTP4Dev mail server that targets development and does not require any setup.
Create class name SMTP.cs then
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
/// <summary>
/// Summary description for SMTP
/// </summary>
public class SMTP
{
private SmtpClient smtp;
private static string _smtpIp;
public static string smtpIp
{
get
{
if (string.IsNullOrEmpty(_smtpIp))
_smtpIp = System.Configuration.ConfigurationManager.AppSettings["smtpIp"];
return _smtpIp;
}
}
public SMTP()
{
smtp = new SmtpClient(smtpIp);
}
public string Send(string From, string Alias, string To, string Subject, string Body, string Image)
{
try
{
MailMessage m = new MailMessage("\"" + Alias + "\" <" + From + ">", To);
m.Subject = Subject;
m.Priority = MailPriority.Normal;
AlternateView av1 = AlternateView.CreateAlternateViewFromString(Body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
if (!string.IsNullOrEmpty(Image))
{
string path = HttpContext.Current.Server.MapPath(Image);
LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
av1.LinkedResources.Add(logo);
}
m.AlternateViews.Add(av1);
m.IsBodyHtml = true;
smtp.Send(m);
}
catch (Exception e)
{
return e.Message;
}
return "sucsess";
}
}
then
on aspx page
protected void lblSubmit_Click(object sender, EventArgs e)
{
//HttpContext.Current.Response.ContentType = "text/plain";
//Guid guid = Guid.NewGuid();
string EmailMessage = "<html>" +
"<head>" +
"<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" +
"</head>" +
"<body style=\"text-align:left;direction:ltr;font-family:Arial;\" >" +
"<style>a{color:#0375b7;} a:hover, a:active {color: #FF7B0C;}</style>" +
"<img src=\"" width=\"190px\" height= \"103px\"/><br/><br/>" +
"<p>Name: " + nameID.Value + ",<br/><br/>" +
"<p>Email: " + EmailID.Value + ",<br/><br/>" +
"<p>Comments: " + commentsID.Text + "<br/><br/>" +
// "Welcome to the Test local updates service!<br/>Before we can begin sending you updates, we need you to verify your address by clicking on the link below.<br/>" +
//"<br/><br/>" +
//"We look forward to keeping you informed of the latest and greatest events happening in your area.<br/>" +
//"If you have any questions, bug reports, ideas, or just want to talk, please contact us at <br/><br/>" +
//"Enjoy! <br/>" + commentsID.Text + "<br/>" +
//"Test<br/>www.Test.com</p>" +
"</body>" +
"</html>";
lblThank.Text = "Thank you for contact us.";
// string Body = commentsID.Text;
SMTP smtp = new SMTP();
string FromEmail = System.Configuration.ConfigurationManager.AppSettings["FromEmail"];
string mailReturn = smtp.Send(EmailID.Value, "", FromEmail, "Contact Us Email", EmailMessage, string.Empty);
//HttpContext.Current.Response.Write("true");
nameID.Value = "";
EmailID.Value = "";
commentsID.Text = "";
}
Below is the solution for you if you do not want to use gmail or hotmail:
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#MyWebsiteDomainName.com", "myIDPassword");
smtpClient.UseDefaultCredentials = true;
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);
Hope it help :)
Server.mappath does not exist. There is no Server object.

I'm having problems with SMTP Authentication in C#

I have an MVC 3 app and everything I try on my new hosting provider ends up throwing this exception:
Server Error in '/' Application.
Mailbox unavailable. The server response was: Authentication is required for relay
I tried using the code from
How can I make SMTP authenticated in C#
which has many up votes, but I still get the exception.
My host has the typical panels that let me create mail accounts. I'm not sure about creating NetworkCredentials, what do I use as the User Name and password? What I've been using is the email address and the password for the email account.
Here's my code:
public static void sendMail(Joiner request) {
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("garbage#stopthedumpcoalition.org", "REDACTED");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("garbage#stopthedumpcoalition.org");
smtpClient.Host = "mail.stopthedumpcoalition.org";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "Join the Coalition request from - " + request.FirstName + " " + request.LastName;
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "Name: " + request.FirstName + " " + request.LastName + "<br>"
+ "EMail: " + request.Email + "<br>"
+ "Wants to Volunteer: " + request.Volunteer.ToString() + "<br>"
+ "Organization: " + request.Organization + "<br>"
+ "Wants to become a Partner: " + request.Partner.ToString() + "<br>"
+ "Comments: " + request.Comments;
message.To.Add("nivram509#gmail.com");
smtpClient.Send(message);
}
Thanks Sani. It was even stupider than that. My Site Host's web panel had two text boxes for changing the password, I I filled both out and hit save.
It also had a checkbox for "change Password" and I never noticed it.
So I had the wrong password. The code is fine. :)

Categories