I am configuring SMTPClient with these codes to use local directory:
EmailHelper.cs
public bool SendMail(string from, string to, string cc, string subject, string body, bool isBodyHtml)
{
try
{
var smtpClient = new SmtpClient();
string pickUpFolder = #"C:\Users\kerem\Documents\Visual Studio 2012\Projects\Blog\Blog\Email";
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
pickUpFolder = mailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
smtpClient.PickupDirectoryLocation = pickUpFolder;
}
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(to));
if (cc != "")
mailMessage.CC.Add(new MailAddress(cc));
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
return true;
}
catch (Exception err)
{
return false;
}
}
EmailHelper.cs in BlogServices Project in my Blog solution. Also there is a Blog Project in the same solution. I have replaced Blog\Blog\Email in pickUpFolder with Blog\Email and Blog\BlogServices\Email but I still have an error of Only absolute directories are allowed for pickup directory. Where is my mistake? Thanks in advance.
Add this to your project's web.config.
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\kerem\Documents\Visual Studio 2012\Projects\Blog\Blog\Email\"/>
</smtp>
</mailSettings>
</system.net>
Alternatively, try deleting this line: pickUpFolder = mailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;, but I suspect you'll have other problems if you go that route.
Related
I am trying to send a mail, in this case a gridview to a specified folder on my machine as to be able to view the message. I am thus sending the mail but it is not ending up in the folder. How can I do this?
I added this to web.config:
<system.net>
<mailSettings >
<smtp deliveryMethod="Network" from="ArianG#lr.co.za">
<network host="staging.itmaniax.co.za"/>
<specifiedPickupDirectory pickupDirectoryLocation="C:\testdump\emaildump\"/>
</smtp>
</mailSettings>
This is my code for sending the gridview. (I presume I do not need SmtpClient as I do not want to connect to a port, either 25 or 587) :
private void MailReport()
{
//*****************************************************
string to = "arianul#gmail.com";
string From = "ArianG#lr.co.za";
string subject = "Report";
string Body = "Good morning, Please view attachment<br> Plz Check d Attachment <br><br>";
Body += GridViewToHtml(GridView1);
Body += "<br><br>Regards,<br>Arian Geryts(ITManiax)";
bool send = sendMail(to, From, subject, Body);
if (send == true)
{
string CloseWindow = "alert('Mail Sent Successfully!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
else
{
string CloseWindow = "alert('Problem in Sending mail...try later!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
//*****************************************************
}
public bool sendMail(string to, string from, string subject, string body)
{
bool k = false;
try
{
MailMessage msg = new MailMessage(from, to);
msg.Subject = subject;
AlternateView view;
SmtpClient client;
StringBuilder msgText = new StringBuilder();
view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");
msg.AlternateViews.Add(view);
msgText.Append(" <html><body><br></body></html> <br><br><br> " + body);
//*****
/*client = new SmtpClient("smtp.gmail.com", 25);
client.Host = "staging.itmaniax.co.za";
client.Port = 25;
//****
client.EnableSsl = true;
client.Send(msg);*/
k = true;
}
Change your mail Setting in web.config to:
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\smtp" />
This should do the trick. Alternativly you could change the setting via tha IIS gui, after you deployed the solution.
Kind regards.
/edit: of course you need a smtp client. The program has to fire the email message out to the smtp server. The message just gets picked up by IIS and stuffed into a folder.
I am using MailMessage to send email from a web application. I believe I have the correct code in to "mask" the from name in the SendEmail() function
public static void SendEmail(string toAddress, string ccAddress, string bccAddress, string subject, string body, MemoryStream attachment, string attachmentName, bool isHtml, string fromAlias = "info#cipollainsurance.com")
{
using (MailMessage message = new MailMessage())
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(AddHeaderAndFooter(subject, body).ToString(), new System.Net.Mime.ContentType("text/html"));
var resources = LoadResources();
foreach (LinkedResource resource in resources)
{
htmlView.LinkedResources.Add(resource);
}
message.AlternateViews.Add(htmlView);
if (!string.IsNullOrEmpty(toAddress))
{
var addresses = toAddress.Split(',', ';');
foreach (string address in addresses)
{
message.To.Add(address);
}
}
if (!string.IsNullOrEmpty(ccAddress))
{
var ccAddresses = ccAddress.Split(',', ';');
foreach (string cc in ccAddresses)
{
message.CC.Add(cc);
}
}
if (!string.IsNullOrEmpty(bccAddress))
{
var bccAddresses = bccAddress.Split(',', ';');
foreach (string bcc in bccAddresses)
{
message.Bcc.Add(bcc);
}
}
if (!string.IsNullOrWhiteSpace(fromAlias))
{
message.Sender = new MailAddress("info#cipollainsurance.com", fromAlias, System.Text.Encoding.ASCII);
}
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = isHtml;
message.From = new MailAddress("info#cipollainsurance.com", "Cipolla Insurance");
if (attachment != null)
{
message.Attachments.Add(new Attachment(attachment, attachmentName));
}
SmtpClient client = new SmtpClient();
client.Send(message);
}
}
However the from email address still says email and email#webedgemedia.com which is what is specified in web.config.
<smtp from="info#cipollainsurance.com" deliveryMethod="Network">
<network host="smtp.gmail.com" enableSsl="true" port="587" password="myPassword" userName="email#webedgemedia.com" />
</smtp>
Can someone identify what I'm missing to send the email out as info#cipollainsurance.com?
I don't believe GMAIL allows you to do that - it makes it pretty trivial to use their services as a SPAM relay otherwise.
The most you can do is set a different REPLY-TO but your GMAIL (account) email is still FROM.
i need solution for this error
i am run that time some error occur there is:Send Email Failed.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. i1sm8651517pbj.70
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
#region "Send email"
protected void btnSendmail_Click(object sender, EventArgs e)
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = "smtp.gmail.com";
//Default port will be 25
smtpClient.Port = 587;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add("muthu17green#gmail.com");
message.Subject = "Feedback";
// CC and BCC optional
// MailAddressCollection class is used to send the email to various users
// You can specify Address as new MailAddress("admin1#yoursite.com")
message.CC.Add("muthu17green#gmail.com");
message.CC.Add("muthu17green#gmail.com");
// You can specify Address directly as string
message.Bcc.Add(new MailAddress("muthu17green#gmail.com"));
message.Bcc.Add(new MailAddress("muthu17green#gmail.com"));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = false;
// Message body content
message.Body = txtMessage.Text;
// Send SMTP mail
smtpClient.Send(message);
lblStatus.Text = "Email successfully sent.";
}
catch (Exception ex)
{
lblStatus.Text = "Send Email Failed.<br>" + ex.Message;
}
}
#endregion
#region "Reset"
protected void btnReset_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtMessage.Text = "";
txtEmail.Text = "";
}
#endregion
}
You need to set the SmtpClient.Credentials property:
smtpClient.Credentials = new NetworkCredentials("yourUserName", "yourPassword");
This is what is used to authenticate in order to send the message. You may also need to ensure that SSL is enabled:
smtpClient.EnableSsl = true;
SmtpClient.Credentials Property MSDN Reference
It seems that you are trying to send an email using GMail, which requires SSL.
See this Google reference post.
So in your web.config, enable SSL this way:
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network host="smtp.gmail.com" port="587" enableSsl="true" userName="YOURUSERNAME" password="YOURPASSWORD" />
</smtp>
</mailSettings>
</system.net>
Alternatively, you can set it programmatically this way:
smtpClient.EnableSsl = true;
I think you forgot to set EnableSSL property to true which is required for gmail.
Here is the sample code:
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(txtFrom.Text);
msg.To.Add(new MailAddress(txtTo.Text));
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpClient mySmtpClient = new SmtpClient();
System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential(txtFrom.Text,txtPwd.Text);
mySmtpClient.Host = "smtp.gmail.com";
mySmtpClient.Port=587;
mySmtpClient.EnableSsl = true;
mySmtpClient.UseDefaultCredentials = false;
mySmtpClient.Credentials = myCredential;
mySmtpClient.Send(msg);
msg.Dispose();
lberr.Text="Message sent successfully";
clrtxt();
}
catch(SmtpException)
{
lberr.Text="SMTP Error handled";
}
}
public void SendMail()
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(MailTo.Text);
mail.From = new MailAddress(MailFrom.Text,"Invoice");
mail.Subject = Subject.Text;
mail.Body = Body.Text;
mail.IsBodyHtml = true;
string FileName = Path.GetFileName(FileUploadAttachments.PostedFile.FileName);
Attachment attachment = new Attachment(FileUploadAttachments.PostedFile.InputStream ,FileName);
mail.Attachments.Add(attachment);
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("Your_Email#Email.com", "Your_Email_Password");
client.Host = "smtpout.secureserver.net";
client.Port = 80;
try
{
client.Send(mail);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
So i've been searching stackoverflow for a way to send emails using a gmail account via a asp website...
I've tried many ways including Sending email in .NET through Gmail which seemed to be the best due to amount of upvotes he got.
However sadly it still doesn't work for me! I keep getting a time out.
Here's my code:
var fromaddress = new MailAddress("from#gmail.com", "from");
var toaddress = new MailAddress("to#address.com", "to");
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.EnableSsl = true;
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
in my web.config I have
<system.net>
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" port="587"/>
</smtp>
</mailSettings>
</system.net>
According to several sites i've visited this should work!!! .. but it doesn't.
Is there still anything i'm doing wrong?
You never set the login add this before your smtpClient.Send() Method.
NetworkCredential NetCrd = new NetworkCredential(youracc, yourpass);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = NetCrd;
Load the web.config via ConfigurationManager if it does not work automatically.
As suggested on this page, try installing telnet to see if you can connect to the mail server. It could be a firewall issue on your server. You can also try using another port as suggested in the link.
Your code seems fine to me.
Try to deliberately enter false credentials. If you get a different errormessage you are connected to gmail and there is a problem there.
If you get the same timeout problem, it is probably not a software thing but a firewall issue.
longshot - update
Perhaps there is a web.config issue? Try to specify everything in code like this. I have this working in real life with Gmail so if this does not work it definitely is a firewall/connection thing.
SmtpClient mailClient = new SmtpClient();
//This object stores the authentication values
System.Net.NetworkCredential basicCredential =
new System.Net.NetworkCredential("username#mydomain.com", "****");
mailClient.Host = "smtp.gmail.com";
mailClient.Port = 587;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCredential;
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("info#mydomain.com", "Me myself and I ");
message.From = fromAddress;
//here you can set address
message.To.Add("to#you.com");
//here you can put your message details
mailClient.Send(message);
Good luck..
Can you try this out?
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromAddress"], ConfigurationManager.AppSettings["displayName"]); //Default from Address from config file
MailAddress toAddress = new MailAddress("abc#gmail.com", "from sender");
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = ConfigurationManager.AppSettings["smtpClientHost"];
//Default port will be 25
smtpClient.Port = int.Parse(ConfigurationManager.AppSettings["portNumber"]); //From config file
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(toAddress);
message.Subject = ConfigurationManager.AppSettings["Subject"]; //Subject from config file
message.IsBodyHtml = false;
message.Body = "Hello World";
smtp.DeliveryMethod = SmtpDeliveryMethod.NetWork
smtpClient.Send(message);
}
catch (Exception ex)
{
throw ex.ToString();
}
The configuration settings would be,
<configuration>
<appSettings>
<add key="smtpClientHost" value="mail.localhost.com"/> //SMTP Client host name
<add key="portNumber" value="25"/>
<add key="fromAddress" value="defaultSender#gmail.com"/>
<add key="displayName" value="Auto mail"/>
<add key="Subject" value="Auto mail Test"/>
</appSettings>
</configuration>
Put these settings EnableSSL = true and defaultCredentials="false" in your web.config settings. Gmail smtp server requires SSL set to true and mailclient.UseDefaultCredentials = false should be false if you are providing your credentials.
Update Web.Config Settings:
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" defaultCredentials="false" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
And check this shorter code to send mail after providing settings in the web.config. even it send email much fast rather then specifying setting while creating the smtpclient setting in the mail sending function.
Public void SendEmail(string toEmailAddress, string mailBody)
{
try
{
MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(toEmailAddress);
mailMessage.Subject = "Mail Subjectxxxx";
mailMessage.Body = mailBody;
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
return "Mail send successfully";
}
catch (SmtpException ex)
{
return "Mail send failed:" + ex.Message;
}
Working very much fine at my side..
var smtpClient = new SmtpClient(gmailSmtpServer, gmailSmtpPort)
{
Credentials = new NetworkCredential(FromGEmailAddress, FromGEmailAddressPassword),
EnableSsl = true
};
try
{
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
catch (Exception exc)
{
// error
return false;
}
I am facing the above-mentioned error while sending emails from windows service. Your suggestion is much appreciated.
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMsg = this.ComposeMailMessage();
smtpClient.Send(mailMsg);
Configuration
<system.net>
<mailSettings>
<smtp from="user1#mycompany.com" deliveryMethod="Network">
<network host="smtpsvr.mycompany.com" port="25" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
Maybe mine is not the answer you're searching, but try this (avoiding IIS):
try
{
// To
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add(to_Address);
// From
MailAddress mailAddress = new MailAddress(from_address);
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = subject;
mailMsg.Body = body;
// Init SmtpClient and send
SmtpClient smtpClient = new SmtpClient(smtp_server, port);
// System.Net.NetworkCredential credentials =
// new System.Net.NetworkCredential(smtp_user, smtp_pwd);
// smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine( ex.Message );
}
You probably need to set the SmtpClient PickupDirectory manually.
There is an example of how to do that in the Lukas Pokorny's answer:
Cannot get IIS pickup directory
Try add the following line to your program. This line needs the IIS Admin and SMTP service running on your desktop.
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
So it will become like this
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMsg = this.ComposeMailMessage();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Send(mailMsg);