Suddenly getting the error Failure Sending Mail in ASP.Net - c#

I am continuously getting this error failure sending mail. I have already tried by changing port 465/25/587 but nothing worked. My credentials are also correct. All these configurations are for outlook. Checked all the ports they are also not blocked. The same code was working fine before but from last couple of days getting this error. Unable to get what's happening in this code.
Below is my code-
protected void btnSubmitClick(object sender, EventArgs e)
{
try
{
if (ddlSubCategory.SelectedIndex > 0)
{
if (Session["sessionID"] != null && Session["sessionID"].ToString().ToUpper().Trim() == "SUBMITTED")
{
// string textForMessage = #"<script language='javascript'> alert('Request Already Submitted for the same...!');</script>";
// ClientScript.RegisterClientScriptBlock(this.GetType(), "Stop", textForMessage); return;
}
if (fupAttachment.HasFile) { ViewState["file1"] = "0"; }
if (ViewState["file1"].ToString() == "0")
{
IssuesCommon issueCommon = new IssuesCommon();
issueCommon.IssueCateId = Convert.ToInt32(ddlSubCategory.SelectedValue);
issueCommon.Status = "OPEN";
issueCommon.LogBy = issueCommon.EmpId = Convert.ToInt32(getEmpDetail().Split('$')[0]);
issueCommon.Description = txtDesc.Text.Trim();
issueCommon.WorkStation = txtWorkStation.Text.Trim();
issueCommon.IPAddress = hfIP.Value;
issueCommon.Contact = txtphn.Text.Trim();
issueCommon.DepartmentId = Convert.ToInt32(Request.QueryString["help"]);
issueCommon.Supervisor = hfSuperId.Value;
string ticket = lblDeskName.Text + "#00" + Convert.ToString(Convert.ToInt32(objBal.getMaxIssueID()) + 1);
issueCommon.TicketNo = ticket;
issueCommon.Priority = (ddlPriority.SelectedValue == "Low" ? ddlSubPriority.SelectedValue : ddlPriority.SelectedValue);
issueCommon.attachmentName = fupAttachment.HasFile ? Server.MapPath("~/image/") + fupAttachment.FileName : null;
if (trSelectClient.Visible == true)
{
issueCommon.clientName = ddlClientList.SelectedValue.ToString() == "--Select--" ? "" : ddlClientList.SelectedValue.ToString();
}
else
{
issueCommon.clientName = "";
}
objBal.InsertIssue(issueCommon);
#region Mail Section
MailMessage mM = new MailMessage();
mM.From = new MailAddress("no-reply#xxxxxxx.com");
mM.To.Add(getDapartmentEmailId());
if (txtAddRecipient.Text != "" && txtAddRecipient.Text != null && trAddRecipient.Visible == true)
{
mM.CC.Add(txtAddRecipient.Text);
}
if (Session["help"] != null)
{
if (Convert.ToString(Session["help"]) == "1")
{
mM.Bcc.Add("abc#xxxxxx.com");
}
}
if (fupAttachment.HasFile)
{
string filename = fupAttachment.FileName;
fupAttachment.SaveAs(Server.MapPath("~/images/") + filename);
Attachment attach = new Attachment(Server.MapPath("~/images/") + filename);
mM.Attachments.Add(attach);
}
mM.Subject = "Issue Ticket#: " + issueCommon.TicketNo + " [Priority: " + issueCommon.Priority + "]";
string mailBody = "Hello," +
"<br/> I am having the below issue: <br/><br> Issue Category : " + ddlSubCategory.SelectedItem.Text
+ " <br/> <br/> Workstation: " + txtWorkStation.Text + " <br/><br/> IP Address : " + txtIP.Text
+ "<br /><br /> Client Name: " + ddlClientList.SelectedValue.ToString().Replace("--Select--", "N/A")
+ "<br /><br /> My ContactNo: " + txtphn.Text
+ "<br/><br/> Description : " + txtDesc.Text.Trim() + "<br/><br/> Thanks, <br/>" + hfEmpid.Value + "/" + username.Text;
mM.Body = mailBody;
mM.IsBodyHtml = true;
mM.Priority = MailPriority.High;
SmtpClient sC = new SmtpClient("smtp.office365.com");
sC.Port = 587;
sC.EnableSsl = true;
sC.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sC.Credentials = new NetworkCredential("email", "password");
sC.Send(mM);
SendMailtoUser(issueCommon.TicketNo, lblUserName.Text.Trim());
Session["sessionID"] = "Submitted"; ViewState["file1"] = "0"; clearView();
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Your request has been submitted successfully');", true);
#endregion
}
else
{
string textForMessage = #"<script language='javascript'> alert('Select Attachment ');</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "UserPopup", textForMessage);
}
}
else { Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Select Issue Category');", true); }
}
catch (Exception ex) {
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('" + ex.Message.Replace("'", "") + "');", true); }
}
Please see the exception screenshot here
enter image description here

if you try this i think sending mail will be successful
var smtpClient = new SmtpClient(hostname, 25);
// userNameShort = "ab", domain = "outlook" for example
var networkCredential = new NetworkCredential(userNameShort, password, domain);
smtpClient.Credentials = networkCredential;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtpClient.EnableSsl = true;
smtpClient.Send(message);

Please can you trying:
SmtpClient sC = new SmtpClient("smtp.office365.com");
after adding
sC.Credentials = new NetworkCredential("email", "password");
then
sC.Port = 587;
//your codes

Related

Exception from HRESULT: 0x80004004 (E_ABORT) at Outlook.Mailitem.getHtmlBody()

I have a custom add-in which gets the body on clicking a button when it got installed. so I am getting this error on a customer machine. code is working fine on my side and for other customers but one customer is facing this problem.
this is my code
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Explorer olExp = olApp.ActiveExplorer();
Selection olSel = olExp.Selection;
string msg = "";
int iterate = 1;
MAPIFolder inbox = null;
if (olSel.Count > 1)
{
MessageBox.Show("Sorry! You can't report more then 1 email at a time", "Report Email");
return;
}
foreach (_MailItem mail in olSel)
{
inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mail.GetInspector.Display(false);
Thread.Sleep(2100);
string screenShot = getScreenShot(mail);
mail.GetInspector.Close(OlInspectorClose.olDiscard);
String msgToShow = "Are you sure you want to report this email as suspicious?";
if (mail != null && mail.Subject != null)
msgToShow += "\n\nSubject : " + mail.Subject.ToString();
DialogResult dr = MessageBox.Show(msgToShow, "Please Confirm", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
msg += reportMail(mail, screenShot, e);
}
else {
return;
}
iterate++;
break;
}
if (!msg.Equals(""))
MessageBox.Show(msg, "Report Email");
else
return;
if (!msg.Contains("Success"))
return;
MailItem moveMail = null;
MAPIFolder subfolder = null;
try
{
subfolder = inbox.Folders["Reported Emails"];
}
catch (System.Exception ex) {
subfolder = inbox.Folders.Add("Reported Emails", OlDefaultFolders.olFolderInbox);
}
foreach (MailItem eMail in olSel)
{
try
{
moveMail = eMail;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
moveMail.Move(subfolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private string reportMail(_MailItem mail, string screenShot, RibbonControlEventArgs e)
{
try
{
var m = Globals.ThisAddIn.Application.GetNamespace("MAPI");
var mailitem = mail;
if (mailitem != null)
{
// Console.WriteLine("Email body ::: " + mailitem.HTMLBody);
String reporterEmail = getReporterEmail(mailitem);
String senderEmailAddress = "";
String senderName = "";
AddressEntry mailsender;
if (reporterEmail.Equals(""))
{
MessageBox.Show("Sorry! This email can't be reported because you are not included in Recipients.", "Report Email");
}
else
{
if (mailitem.SenderEmailType == "EX")
{
mailsender = mailitem.Sender;
if (mailsender != null)
{
if (mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
ExchangeUser exchUser = mailsender.GetExchangeUser();
if (exchUser != null)
{
senderEmailAddress = exchUser.PrimarySmtpAddress;
senderName = exchUser.Name;
}
}
}
}
else
{
senderEmailAddress = mailitem.SenderEmailAddress;
senderName = mailitem.SenderName;
}
String emailHeader = mailitem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
String emailBody = mailitem.Body.Replace("%"," percent").Replace("#","").Replace("|", "");
//String res = HttpPost(Properties.Settings.Default.address, "ReporterEmail=" + reporterEmail + "&suspectedName=" + senderName + "&FromEmail=" + senderEmailAddress
// + "&ToEmail=" + mailitem.To + "&Subject=" + mailitem.Subject + "&EmailBody=" + emailBody + "&AttachmentName=" + GetAttachments(mailitem)
// + "&reporter=" + reporterEmail + "&emailHeader=" + emailHeader + "&mailImage=" + screenShot);
String htmlBody = mail.HTMLBody;
MessageBox.Show(htmlBody);
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("ReporterEmail", reporterEmail);
postParameters.Add("suspectedName", senderName);
postParameters.Add("FromEmail", senderEmailAddress);
postParameters.Add("ToEmail", mailitem.To);
postParameters.Add("Subject", mailitem.Subject);
postParameters.Add("EmailBody", emailBody);
List<String> attachmentDetails = GetAttachments(mailitem);
postParameters.Add("AttachmentName", attachmentDetails[0]);
postParameters.Add("reporter", reporterEmail);
postParameters.Add("emailHeader", emailHeader);
postParameters.Add("mailImage", screenShot);
string res = HttpPost(Properties.Settings.Default.serverAddress+ "/PhishRod-portlet/reporter", postParameters, htmlBody,attachmentDetails[1]);
return res + "\n";
}
}
}
catch (System.Exception ex)
{
log.Error(ex);
return "Error: " + ex + "-- - " + ex.StackTrace.ToString() + "\n";
}
return "";
}
In the event handler of your button I see the following lines of code:
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
There is no need to create a new Outlook Application instance in the add-in. Instead, you need to use the Application property which doesn't trigger a security issue when dealing with OOM from external applications:
var app = Globals.ThisAddIn.Application

Email Works fine but got two emails at same time?

I try to send email, below code works fine but email sends twice at a time. I tried a lot but I don't know where I made a mistake.
RTElapsedTime.cs:
public void Elapsed()
{
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
T1.Interval = 60000;
T1.Enabled = true;
}
public void T1_Elapsed(object source, ElapsedEventArgs e)
{
try
{
MatchingTime = DateTime.Now.ToString("HH:mm");
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString());
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count);
foreach (DataRow r in dt.Rows)
{
T1.Enabled = false;
RTEmailManagement(r);
T1.Enabled = true;
}
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed.");
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message);
}
}
DataTable dataRPT1 = new DataTable();
public DataTable ReportGeneration2(EmailDTO EETO)
{
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType);
return dataRPT1;
}
public void RTEmailManagement(DataRow dr)
{
EDTO = null;
EDTO = new EmailDTO();
MatchingTime = DateTime.Now.ToString("HH:mm");
EDTO.SecondTime = MatchingTime;
EDTO.ScheduleTime = dr["rshtime"].ToString();
EDTO.ToEmails = dr["rsh_altrntmail"].ToString();
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
EDTO.Subject = dr["rsh_subjct"].ToString();
EDTO.ReportID = dr["reportid"].ToString();
EDTO.Departments = dr["rsh_dept"].ToString();
EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString());
EDTO.weekly = dr["rsh_day"].ToString();
EDTO.Monthly = dr["rsh_dayofmnth"].ToString();
EDTO.Day = dr["xday"].ToString();
EDTO.Body = dr["rsh_body"].ToString();
EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString());
CompanyID = Int32.Parse(dr["Company_id"].ToString());
dataRPT1 = ReportGeneration2(EDTO);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count);
foreach (DataRow r in dataRPT1.Rows)
{
EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray();
EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray();
//EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString();
EDTO.ToEmails1 = r["email_addr"].ToString();
EDTO.LateArrival = r["LateArrivals"].ToString();
if (EDTO.ScheduleTime == EDTO.SecondTime)
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched");
switch (Convert.ToInt32(EDTO.ReportType))
{
case 0:
case 1:
EmailConfiguration(CompanyID, EDTO);
break;
case 2:
//TraceImplogs.TraceLTService("tyoe 2 new");
EmailConfiguration(CompanyID, EDTO);
break;
case 3:
// TraceImplogs.TraceLTService("tyoe 3 new");
EmailConfiguration(CompanyID, EDTO);
break;
default:
break;
}
}
}
// else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching");
}
public void EmailConfiguration(int compid, EmailDTO EDTO)
{
try
{
ConfigDTO mlDTO = new ConfigDTO();
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid);
RTMailProcessing Mprocess = new RTMailProcessing();
mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString();
mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString();
mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString();
mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString());
Mprocess.EmailProcessing(mlDTO, EDTO);
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message + " Email Error");
}
}
Email processing cs code.
RtMailprocessing.cs:
public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO)
{
RTMsg.language(EDTO.langcode);
conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd);
// TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd);
SmtpClient smtp = new SmtpClient
{
Host = conDTO.ConfigHost,
Port = conDTO.ConfigPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd)
// Timeout = 30000,
};
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// TraceImplogs.TraceLTService("Entered inside");
if (EDTO.ToEmails != "")
{
using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body))
{
for (int k = 0; k < EDTO.CcEmails.Length; k++)
{
if (EDTO.CcEmails[k] != "")
{
message.CC.Add(EDTO.CcEmails[k].TrimEnd(';'));
}
else
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty");
}
}
message.CC.Add(EDTO.ToEmails);
message.Subject = ""; message.Body = "";
message.Subject = EDTO.Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// ReportGeneration(EDTO);
string EmailBody = "";
if (attach != null)
{
message.Attachments.Add(attach);
string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
/*****with attachment***/
foreach (string lines in RepBody)
{
EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>";
}
message.Body = "Email Testing";
message.BodyEncoding = System.Text.Encoding.UTF8;
//message.Attachments.Dispose();
//message.Dispose();
}
if (dataRPT.Rows.Count < 1)
{
message.Body ="Test Email";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Attachments.Clear();
}
message.IsBodyHtml = true; //Send this as plain-text
smtp.Send(message);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully.");
message.CC.Clear();
//((IDisposable)smtp).Dispose();
//message.Attachments.Dispose();
//message.Dispose();
}
}
}
When I debug with breakpoint loop run single time only but I got two email. I don't know where I made exactly mistake.
Thanks in advance.
I'm going to take a guess, you're not unsubscribing the event:
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
You need to unsubscribe it:
T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed);
The email server processed both messages and delivered them at the same time.

Send Email from Windows Service: Transaction failed. the server response was 5.7.1 client host rejected access denied

The below code is working fine from Windows Form, but not working from Windows Services.
The service is running on Windows XP.
I have tried changing the log on user, but did not work.
Error: Transaction failed. the server response was 5.7.1 client host
rejected access denied
private void SendEmailToHO()
{
try
{
int mailSentSuccessfully = 0;
MailAddress to = new MailAddress(mailTo);
MailAddress from = new MailAddress(mailFrom);
using (MailMessage mail = new MailMessage(from.Address, to.Address))
{
int attachmentCount = 0;
try
{
foreach (string fileName in fileEntries)
{
Attachment attachment = new Attachment(fileName);
mail.Attachments.Add(attachment);
attachmentCount++;
}
SmtpClient client = new SmtpClient(mailHost, port);
if (enableSSL == "Y")
{
client.EnableSsl = true;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(mailUser, mailPassword);
mail.Subject = "Email Subject " + clientID;
mail.Body = "Attached please find the files: " + clientIDTitle;
if (attachmentCount > 0)
{
//
client.Send(mail);
//if no error, this code will work.
mailSentSuccessfully = 1;
new MyApp.LogWriter("Sent mail to " + to.Address + ", \nAttachment count = " + attachmentCount);
}
else
{
new MyApp.LogWriter("Attachment count = " + attachmentCount);
}
}
catch (Exception ex)
{
new MyApp.LogWriter("Send mail failed. Cause: " + ex.Message
+ "\n Inner Exception: " + ex.InnerException);
}
}
}
catch (System.Exception ex)
{
new BTCClient.LogWriter("Email Error '" +
ex.Message + "'");
}
}
I was facing the same issue, To resolve this issue you need to contact your email server's service provider and tell them to give access to your server IP.

How i can create a share facebook button inside to an email with C#?

I am trying to create a facebook share button inside to an email and share the attached video via C#.
First of all, I have attached into the email the video which i am trying to send.
But i can't create via C# the facebook button that i want to share the video.
You may find my source code so far :
public static string logopath = Path.Combine(Application.StartupPath, "logo.png");
public static string videopath = Path.Combine(Application.StartupPath, "test.mp4");
private void button1_Click_1(object sender, EventArgs e)
{
string usermail = textBox1.Text;
bool isUsermailNull = usermail.Equals("");
Console.Out.WriteLine("The variable is " + isUsermailNull);
if (isUsermailNull.Equals(false))
{
try
{
MailAddress m = new MailAddress(usermail);
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("myemailaccount#gmail.com");
message.To.Add(new MailAddress(usermail));
message.Subject = "SUBJECT";
message.IsBodyHtml = true;
Attachment inlineLogo = new Attachment(logopath);
Attachment inlineLogo2 = new Attachment(videopath);
message.Attachments.Add(inlineLogo);
message.Attachments.Add(inlineLogo2);
string contentID = "Image";
string contentID2 = "Image2";
inlineLogo.ContentId = contentID;
inlineLogo2.ContentId = contentID2;
//To make the image display as inline and not as attachment
inlineLogo.ContentDisposition.Inline = true;
inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inlineLogo2.ContentDisposition.Inline = true;
inlineLogo2.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
//To embed image in email
//string pass = "123456";
message.Body = "<html><body> <h1 align=\"center\"><img src=\"cid:" + contentID + "\"> </h1><video width=\"400\" controls><source src=\"cid:" + contentID2 + "\" type=\"video/mp4\">Your browser does not support HTML5 video.</video> <h1 align=\"center\">Project</h1> "
+ " <h2 align=\"center\"> NameofProject </h2><h2 align=\"center\">You may find attached your video</h2><div id=\"fb-root\"></div><script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7\"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class=\"fb-video\" data-href=\"cid:" + contentID2 + "\" data-width=\"500\" data-show-text=\"false\"><div class=\"fb-xfbml-parse-ignore\"><blockquote cite=\"cid:" + contentID2 + "\">MyProject </blockquote> </div> </div> <h3 align=\"center\"> Thank you</h3> <h2 align=\"center\">Details</h2> <h2 align=\"center\"> Mail us : myemailaccount#gmail.com</h2> </body></html>";
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("myemailaccount#gmail.com", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Timeout = 5000000;
smtp.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex.Message);
}
this.Close();
}
catch (FormatException)
{
MessageBox.Show("You haven't put correct email address. Try again!!!!");
}
//Kill all on screen keyboards
Process[] oskProcessArray = Process.GetProcessesByName("TabTip");
foreach (Process onscreenProcess in oskProcessArray)
{
onscreenProcess.Kill();
}
}
else
{
MessageBox.Show("The textbox is null. Please insert an appropriate email address");
}
}
Thank you in advance
You need add in body a hmtl <a> with a url that contains your file like for example:
Share in Facebook

how to solve non-local email authentication?

in 3.5 .Net Framework i have a problem to sending an email on server.
Code-
MailMessage message = new MailMessage();
message.From=new MailAddress("CMC Enquiry" + "<my1#domain.in>");
message.To.Add(new MailAddress("vishalpatel8086#gmail.com"));
message.CC.Add(new MailAddress("varun_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
// try
// {
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
// }
// catch
// {
// Label5.Text = "Low Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
// }
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
This code is working my other web hosting server with my different website but is not working with new web site . A error is being occured like -
Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.
Error Is -
Line 83: SMTPServer.Send(message);
Source File: c:\inetpub\vhosts\cmcent.in\httpdocs\enquiry.aspx.cs
Line: 83
Your SmtpClient code needs to be revised as follow:
//Set your smtp client settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.yourdomain.com"; //set with your smtp server
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail#yourdomain.com", "fromEmailPassword");
smtp.Timeout = 20000;
}
// Now send your email with this smtp
smtp.Send(message);
Optionally you can also try to enable/disable ssl & changing the port.

Categories