How to download attachment from email link - c#

I am sending an email with a link that a customer will click and the zip file will get downloaded. but the issue now is that, when I click the link, nothing happens or the zip file doesn't get downloaded. I have searched around but I didn't get what am looking for.
The zip file does exist in the file server \127.0.0.1\Folder1...
How can I download a zip file from a link?
This is my code
public void SendingEmail(string emailTo, string subject, string body, string ZipeFileName = null)
{
string emailHost = "myhost";
string fromEmail = "myemail#domain";
emailTo = "test#gmail.com";
try
{
WebClient myClient = new WebClient();
ZipeFileName = "ApplicationDocuments.zip";
var filePath = #"\\127.0.0.1\Folder1\" + ZipeFileName + "";
var newFileName = Path.GetFileName(filePath);
var DownLoadlink = "<a download href='" + filePath + "'>Click me to DownLoad<\a>";
myClient.DownloadFileAsync(new Uri(filePath), newFileName);
SmtpClient smtp = new SmtpClient(emailHost, 25)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
};
using (var message = new MailMessage(fromEmail, emailTo)
{
Subject = subject,
Body = "Thank for downloading your file. To download, please " + DownLoadlink + "",
})
{
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
smtp.Send(message);
}
#endregion
//End
}
catch (Exception ex)
{
throw ex;
}
}

The folder on localhost (127.0.0.1) is not available from outside of your computer.
Place your file on your portal or ftp site and add the proper address with http(s) or (s)ftp protocol.
Alternatively you can use a shared folder on your computer but this must be accessible from the internet (or where your customers are) what is not recommended.

Related

Send email using c#

I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion

Mail sending in C#is not working in release version

Please I have a working code which send mails correctly only when I execute the application from visual studio, but when I generate the .exe file and install it, I'm not able to recieve the email ! I think it's not problem coming from code, but maybe something else.
a PDF file generated using NReco.Generator and attached to each mail (it's not problem of access because i'm able to send the same files to Box without problem).
What can be the problem ? everything working well in Visual Studio, but not after installing !
This is the code to generate and send file :
void EnvoyerDOCAsync(string path)
{
SmtpClient MyMail = new SmtpClient(ConfigurationManager.AppSettings["server"], Convert.ToInt16(ConfigurationManager.AppSettings["port"]));
MyMsg = new MailMessage();
MyMsg.Priority = MailPriority.High;
MyMsg.From = new MailAddress(ConfigurationManager.AppSettings["mail"], "Sesrvice Mailing");
foreach (Fonction item in fonction.getFonctions())
{
MyMsg.To.Add(new MailAddress(item.FonctionMail, item.FonctionName));
}
MyMsg.Subject = "Hello";
MyMsg.Body = "Bonjour";
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.BodyEncoding = Encoding.UTF8;
MyMail.UseDefaultCredentials = false;
MyMail.Timeout = (60 * 5 * 1000);
NetworkCredential MyCredentials = new NetworkCredential(ConfigurationManager.AppSettings["sso"], ConfigurationManager.AppSettings["pass"]);
MyMail.Credentials = MyCredentials;
if (File.Exists(path))
{
if (path != null)
{
Attachment attachment = new Attachment(path, MediaTypeNames.Application.Octet);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = Path.GetFileName(path);
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
MyMsg.Attachments.Add(attachment);
MyMail.SendAsync(MyMsg, null);
MyMail.SendCompleted += MyMail_SendCompleted;
}
}
}
//Execute this after mail is sended to dispose the Msg and show validation message.<br/>
private void MyMail_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MyMsg.Dispose();
MessageBox.Show("The mail was sended succesfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Thank you.

Possible to temporarily store a file locally before sending to ftp server?

I've got an ASP control for file upload. When the user posts it, it's first locally stored on where I run the website and then I copy it to a remote ftp server.
However, is it possible to remove it from the local server once it's been copied to the ftp server? I'm thinking like storing it in a ~temp folder, but I can't get that to work. As of now I need to create a folder within my project called "temp". Any ideas? Here the method:
String id = Request.QueryString["ID"];
String path = Server.MapPath("~/temp/");
String filename = Path.GetFileName(fuPicture.PostedFile.FileName);
if (fuPicture.HasFile)
{
try
{
if (
fuPicture.PostedFile.ContentType == "image/jpeg" ||
fuPicture.PostedFile.ContentType == "image/png" ||
fuPicture.PostedFile.ContentType == "image/gif"
)
{
fuPicture.PostedFile.SaveAs(path + fuPicture.FileName);
}
else
{
lblFeedback.Text = "Not allowed file extension";
}
}
catch (Exception ex)
{
lblFeedback.Text = "Error when uploading";
}
path += fuPicture.FileName;
String ftpServer = "ftp://xxxx:xxxx";
String userName = "xx";
String password = "xx";
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create(new Uri("ftp://xxxx:xxxx/" + id));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential(userName, password);
using (var resp = (FtpWebResponse)request.GetResponse())
{
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(userName, password);
client.UploadFile(ftpServer + "/" + id + "/" +
new FileInfo(path).Name, "STOR", path);
}
You can call client.UploadData() to upload a byte array from memory, without involving your local disk at all.
Why you don't do a file.delete after the using statement?

Send Email with C#

I am using this code to send an email with an attachment when a button is clicked in my windows 8 application
For this I am using the EASendMail SMTP component which I had to install and reference in my app.
private async void btnSend_Click(object sender, RoutedEventArgs e)
{
btnSend.IsEnabled = false;
await Send_Email();
btnSend.IsEnabled = true;
}
private async Task Send_Email()
{
String Result = "";
try
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Set sender email address, please change it to yours
oMail.From = new MailAddress("test#emailarchitect.net");
// Add recipient email address, please change it to yours
oMail.To.Add(new MailAddress("support#emailarchitect.net"));
// Set email subject
oMail.Subject = "test email from C# XAML project with file attachment";
// Set Html body
oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";
// get a file path from PicturesLibrary,
// to access files in PicturesLibrary, you MUST have "Pictures Library" checked in
// your project -> Package.appxmanifest -> Capabilities
Windows.Storage.StorageFile file =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");
string attfile = file.Path;
Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
// if you want to add attachment from remote URL instead of local file.
// string attfile = "http://www.emailarchitect.net/test.jpg";
// Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
// you can change the Attachment name by
// oAttachment.Name = "mytest.jpg";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test#emailarchitect.net";
oServer.Password = "testpassword";
// If your SMTP server requires TLS connection on 25 port, please add this line
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// If your SMTP server requires SSL connection on 465 port, please add this line
// oServer.Port = 465;
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
await oSmtp.SendMailAsync(oServer, oMail);
Result = "Email was sent successfully!";
}
catch (Exception ep)
{
Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
}
// Display Result by Diaglog box
Windows.UI.Popups.MessageDialog dlg = new
Windows.UI.Popups.MessageDialog(Result);
await dlg.ShowAsync();
}
But when I click the button, I get an error message "Failed to send email with the following error: Access is denied"
How do I fix this?
EDIT:
After enabling the pictures library I know get this message:
EDIT:
I did some further work and noticed that the email send fine without the attachment.
It works without this code:
Windows.Storage.StorageFile file =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");
string attfile = file.Path;
Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
But I need the attachment to be sent also.
How do I fix this?

is not a valid virtual path in SiteMap

hello i want to send an mail of image from Asp.net.
i got an error like this :: 'http://domain-name.com/slideshow/original/Jellyfish.png' is not a valid virtual path.
my code is :
try
{
string _SenderEmailID = ReciverEmailID.Text.ToString();
string _ReciverEmailID = ReciverEmailID.Text.ToString();
string _Sender = FullName.Text.ToString();
string post = "JellyBeans.png";
string ImagePath = "http://www.domain-name.com/slideshow/original/";
string iImage = ImagePath + post;
img1.ImageUrl = ImagePath;
MailMessage mail = new MailMessage();
mail.To.Add(_ReciverEmailID);
mail.From = new MailAddress(_SenderEmailID);
mail.Subject = _Sender + " sent you a mail from 'www.domain-name.com";
string Body = "<img alt=\"\" hspace=0 src=\"cid:imageId\" align=baseline border=0 >";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
LinkedResource imagelink = new LinkedResource(Server.MapPath(ImagePath)+ #post, "image/png");
imagelink.ContentId = "imageId";
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Remove
Server.MapPath
from the line
LinkedResource imagelink = new LinkedResource(Server.MapPath(ImagePath)+ #post, "image/png");
Server.MapPath is used when the path is in your application, a virtual path. Your image url is a direct url or physical path so MapPath is not needed.
Returns the physical file path that corresponds to the specified
virtual path on the Web server.
You would use MapPath if your image was in your VisualStudio solution.

Categories