Sending Email with attachment without saving the attachment c# / ASP.NET - c#

I am trying to send an email with an attachment that will be uploaded by the user and then sent to an admin email.
I have got this configured correctly on IE 11 but however with Chrome/Firefox there is limitations with the FilePath it provides. As IE 11 provides the full file path it allows my function to work.
Is there a possible way round this for Chrome/Firefox.
Mail Message code:
protected void Submit_Click(object sender, EventArgs e)
{
using (MailMessage message = new MailMessage())
{
if (Attachment1.HasFile == false)
{
message.From = new MailAddress(Environment.UserName + "#domain");
message.To.Add(new MailAddress("MyEmail"));
message.IsBodyHtml = true;
message.Subject = "New Request from self service portal: " + Summary.Text.ToString();
message.Body = "Customer Name:</br>Customer Username:" + Environment.UserName + "</br>" + DetailedSummary.Text.ToString();
SmtpClient client = new SmtpClient();
client.Host = "IP ADDRESS";
client.Send(message);
} else {
message.From = new MailAddress(Environment.UserName + "#domain");
message.To.Add(new MailAddress("myemail"));
string file = Attachment1.PostedFile.FileName;
message.Attachments.Add(new Attachment(file));
message.IsBodyHtml = true;
message.Subject = "New Request from self service portal: " + Summary.Text.ToString();
message.Body = "Customer Name:</br>Customer Username:" + Environment.UserName + "</br>" + DetailedSummary.Text.ToString();
SmtpClient client = new SmtpClient();
client.Host = "IP ADDRESS";
client.Send(message);
}
}
}
This is where the user will specify which file will be uploaded and will not be a static file being uploaded every time. Meaning, i will need the filepath from the FileUpload.

HttpPostedFile.FileName "Gets the fully qualified name of the file on the client."
During development on your machine (and using a browser that actually sends the full path, which proper browsers don't) that may work, but as soon as you deploy it on a server it'll break.
The easiest way would be to use the new Attachment(Attachment1.PostedFile.InputStream, "attachmentname") constructor to directly stream the uploaded file into your attachment without having to temporarily save it yourself.

Related

error in email sending via cloud

I have deployed my website to azure cloud and I am trying to send emails to my client. When I have tested this on local host it works properly but on moving to cloud it shows several errors like sometimes:
-> connection time out and i have declared timeout as 150000
->The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. (I have made less secure app allowed to mail account)
Here I am attaching my code. Please review it and suggest a way to resolve it.
Thank you all in advance.
protected void Button2_Click(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
MailAddress from = new MailAddress("bvpcsccloud#gmail.com");
MailAddress to = new MailAddress(Label7.Text);
string subjectText = "E-appointment request";
string bodyText = #"Hi, This mail is for the request of e-appointment from our patient:"+TextBox4.Text.ToString()+"<br />"+ "The patient has age:";
bodyText += TextBox5.Text.ToString()+"<br /> Disease symbols are"+TextBox2.Text.ToString()+"<br /> Disease name:"+ TextBox3.Text.ToString();
bodyText += "<br />Patient address is" + TextBox1.Text.ToString();
bodyText += "<br /> preffered date choosen by patient is" + DropDownList1.SelectedItem.Text + "-" + DropDownList2.SelectedItem.ToString() + "-" + DropDownList3.SelectedItem.Text;
msg.To.Add(to);
msg.From = from;
msg.Subject = subjectText;
msg.Body = bodyText;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("bvpcsccloud#gmail.com", "password");
//smtp.UseDefaultCredentials = false;
try
{
smtp.EnableSsl = true;
smtp.Timeout = 150000;
smtp.Send(msg);
smtp.Dispose();
Response.Redirect("~/appointment_booked.aspx");
}
catch (Exception ex)
{
throw ex;
}
}

Progress status of file upload in smtpClient [duplicate]

I am using this function to send mails via gmail.
private bool uploadToGmail(string username, string password , string file ,
string backupnumber)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("jain#gmail.com");
mail.To.Add("jain#gmail.com");
mail.Subject = "Backup mail- Dated- " + DateTime.Now + " part - " +
backupnumber;
mail.Body = "Hi self. This mail contains \n backup number- " +
backupnumber + " \n Dated- " + DateTime.Now ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(file);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials =
new System.Net.NetworkCredential("jain#gmail.com", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Timeout = 999999999;
SmtpServer.Send(mail);
// MessageBox.Show("mail Sent");
return true;
}
Now I want to show a progress bar (in case there is a large attachment) to show the upload . Is this possible ? I think I know how to use a progress bar, but don't know how to use it with Smtpclient.send() .
any help ?
Thanks
You should use SendAsync and subscribe to SendCompleted, to know, when the sending your mail completed. There is no way to get the progress of the send process, though...

Emails not sent due to SMTP Exception

I have a general mailbox that could be used to send emails from my website. It has stopped working and throws an exception. The following is a screenshot of the error.
error http://img7.imageshack.us/img7/7227/42097647.png
The code is
protected void Submit_Click(object sender, EventArgs e)
{
if (ValidateBox.Text == "6")
{
MailMessage message = new MailMessage();
message.From = new MailAddress(EmailBox.Text.ToString());
message.To.Add(new MailAddress("praveendaniel86#gmail.com"));
message.Subject = "Message via CAM Website General Mailbox";
string body = "Name: " + NameBox.Text.ToString() + Environment.NewLine + Environment.NewLine +
"Home Tel: " + HomeTelBox.Text.ToString() + Environment.NewLine + Environment.NewLine +
"Work Tel: " + WorkTelBox.Text.ToString() + Environment.NewLine + Environment.NewLine +
"Comment/Question: " + CommentBox.Text.ToString();
message.Body = body;
SmtpClient client = new SmtpClient();
client.Send(message);
Response.Redirect("~/Thank-You.aspx");
}
else
{
Label1.Visible = true;
}
}
Could this be an error from the SMTP Client mentioned in my webconfig, How can I check if its working fine ? Thanks.
You are not setting up the Network Credentials. In other words, you're not authenticating the email.
NetworkCredential myCredentials = new NetworkCredential(
"myemail#domain.com","myPassword","mail.myDomainName.com");
client.Credentials = myCredentials;
This is a configuration issue.
The SMTP server specified in your web.config (system.net > mailSettings > smtp) is not configured for relaying. You have two options to fix this:
Configure the SMTP server to allow relaying for the IP address of your web server (only!).
Send SMTP credentials with SmtpClient (see Dave's answer for that).

GoDaddy's SMTP server to send email Error

I want to send email with my web application. It is published on rackspace dedicated server but I'm using GoDaddy's SMTP server to send email.
The fault I'm getting is:
System.Net.Mail.SmtpFailedRecipientException: Mailbox name not allowed. The server response was: sorry, relaying denied from your location [xx.xx.xxx.xx] (#5.7.1)
This is my code
SmtpClient client = new SmtpClient("relay-hosting.secureserver.net", 25);
string to ="rpanchal#itaxsmart.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new System.Net.NetworkCredential("EmailId#domain.com","**");
MailAddress fromAddress = new MailAddress("myEmailId#domain.com", "CompanyName");
MailMessage message = new MailMessage();
message.From = fromAddress;
message.To.Add(to);
message.Body = "This is Test message";
message.Subject = "hi";
client.Send(message); message.Dispose(); return "Email Send";
Should I do any configuration on dedicated server?
Are you testing locally? If yes, then your SMTP server may not allow relaying. Do not worry when you will deploy the application there won't be any problem.
If you are hosting with RackSpace you should use the SMTP RackSpace recommends for sending from their servers. Unfortunately, you can only use relay-hosting.secureserver.net if you are sending from go Daddy Shared or 4GH hosting.
Start trying to change your port 465 instead 25.
Or remember Relay-hosting is very limited to 250 emails per day and not accept remote connections so easy. Check if you can use SSL connection.
That is so simple:
You must focus on smtp host, port, ssl...
Change smtp host to: relay-hosting.secureserver.net
And DELETE port and ssl, thats all...
Do not use smtp port and smtp ssl true or false
var fromAddress = "mailfrom#yourdomain";
// any address where the email will be sending
var toAddress = "mailto#yourdomain";
//Password of your mail address
const string fromPassword = "******";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = "From: " + TextBox2.Text + "\n";
body += "Email: " + TextBox3.Text + "\n";
body += "Subject: " + TextBox4.Text + "\n";
body += "Message: \n" + TextBox5.Text + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "relay-hosting.secureserver.net";
**//Warning Delete =>//smtp.Port = 80;**
**//Warning Delete =>//smtp.EnableSsl = false;**
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);

Send email works locally, but not from remote server

I am attending to send email via the following function and while it works fine when I run it from the local server, it fails when I run it remotely. What might be causing this problem?
private void SendEmail()
{
try
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient("smtp.gmail.com",587);
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
NetworkCredential loginInfo = new NetworkCredential("xx#gmail.com", "xxxx");
message.From = new MailAddress("xx#gmail.com", "xx");
message.To.Add(new MailAddress("yyy#zzz.ac.in","Mail"));
message.IsBodyHtml = true ;
string emailContent = "ICHE 2010 - Abstract Received <br><br>Title: " + Abstract_Title.Text + "<br><br>Author: " + TxtAuthor_FirstName.Text + "_" + TxtAuthor_LastName.Text + "<br><br>Abstract in pdf format attached with this email. <br><br> ICHE2010 Website";
message.Body = emailContent;
message.Subject = "ICHE 2010 - Abstract Received";
string FileName = Server.MapPath(Request.ApplicationPath + "\\AbstractPdfs" + "\\" + abstractBO.AbstractFileNameWithTicks);
Attachment attachmentpdf = new System.Net.Mail.Attachment(FileName);
message.Attachments.Add(attachmentpdf);
client.EnableSsl = true;
client.Send(message);
}
catch (SmtpException smtpex)
{
throw smtpex;
}
catch (Exception ex)
{
throw ex;
}
}
May be the firewall is blocking your application from sending email using the port. Or your remote server may not have internet connection. There can be many reasons for this. Please explain more.
You need to check two things:
From your code, check to see if port 587 is not blocked, or is enabled
Also try opening port 25, which is the port traditionally used by SMTP

Categories

Resources