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.
Related
I have a asp.net mvc site hosted in godaddy, but email sending is not working. In server code I writed the following
var emailmessage = new System.Web.Mail.MailMessage()
{
Subject = subject,
Body = body,
From = from,
To = to,
BodyFormat = MailFormat.Html,
Priority = MailPriority.High
};
SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);
In web config I added the code
<system.net>
<mailSettings>
<smtp from="admin#flex.am">
<network host="relay-hosting.secureserver.net"/>
</smtp>
</mailSettings>
</system.net>
What can I do else?
Thanks!
Below snippet works for me. try this code and if it don't work for you, can you log whole exception message.
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = new MailAddress(txtEmail.Text);
// Recipient e-mail address.
Msg.To.Add("admin#abc.com");
//Msg.Subject = txtSubject.Text;
Msg.Body ="some body message";
SmtpClient smtp = new SmtpClient();
smtp.Host = "relay-hosting.secureserver.net";
smtp.Send(Msg);
var senderEmail = new MailAddress("Your email", "Your Name");
var receiverEmail = new MailAddress("Receiver email", "Receiver name");
var password = "your password"; //I used here APP password
var subject = "Subject";
var body = #"<html><body><p>Dear XYZ,</p></body></html>";
using (SmtpClient client = new SmtpClient
{
Host = "relay-hosting.secureserver.net",
Port = 25,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(senderEmail.Address, password)
})
using (var message = new MailMessage(senderEmail, receiverEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
client.Send(message);
I am using This post and This Post to create simple email sending Application on c# console App. But I am getting error when sent email on gmail ...
{"A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond XXX"}
Here is my Code :
class Program
{
private static string to = "XXX#gmail.com";
private static string from = "XXX#gmail.com";
private static string subject="07/10/14";
private static string body;
private static string address = "XXX#gmail.com";
static void Main(string[] args)
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials =
new System.Net.NetworkCredential(address, "YYYYY");
smtp.Send(mail);
Console.WriteLine("Sent");
Console.ReadLine();
}
}
My App.Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
</appSettings>
<system.net>
<mailSettings>
<smtp from="XXX#gmail.com">
<network defaultCredentials="false"
userName="XXX#gmail.com"
password="YYYYY"
host="smtp.gmail.com" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
I have read similar post ..Some suggest convert url into stream ..I did not get it ..Some says problem might be in internet connection ..other says set smtp server to 587 ..I have applied all changes ..still it shows same error
Please Suggest
I have Solved this problem ...
Just use your Hosting Company Smtp and Port ..not gmail or other one..If you are sending from a hosting company ....Consult your IT Desk for providing your company smtp address and port ..I did that..that solved the Issue
This is My Working Code ..it is also sending to gmail by company SMTP
class Program
{
private static string to = "XXXXr#youHostingComapny.com";
private static string from = "YYYYY#youHostingComapny.com";
private static string subject = "test Mail sent By Code";
private static string body = "Mail sent By Code";
static void Main(string[] args)
{
try
{
MailMessage mail = null;
using (mail = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
mail.Subject = subject;
mail.Body = body;
mail.To.Add("ZZZZZZZZ#gmail.com");
SmtpClient smtpMail = null;
using (smtpMail = new SmtpClient("HostingComapny smtp Address"))
{
smtpMail.Port = Hosting Company Port No.;
smtpMail.EnableSsl = false;
smtpMail.Credentials = new NetworkCredential("youruserName", "yourPassword");
smtpMail.UseDefaultCredentials = false;
// and then send the mail
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpMail.Send(mail);
Console.WriteLine("sent");
Console.ReadLine();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
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.
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.
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;
}