الأربعاء، 1 مايو 2013

Send Email Attachment Using Stream

we need to send email with attachment and we didn't need to save this file to computer first and take the path 
of file in function of send email.
to solve this issue:
1-  


public void SendHtmlMail(string To, string Subject, string Body, string AttachFile, byte[] FileStream)
    {
        string SMTPServe = "smtp.gmail.com";
        string From = "email@gmail.com";
        string fromPassword = "password";
        int Port = "587";
        // smtp settings
        MailMessage message = new MailMessage(From, To, Subject, Body);

        message.IsBodyHtml = true;

        Stream ContentStream = new MemoryStream(FileStream);
        if (!string.IsNullOrEmpty(AttachFile))
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ContentStream, Path.GetFileName(AttachFile));
            message.Attachments.Add(attachment);
        }

        var smtp = new System.Net.Mail.SmtpClient();
        {
            smtp.Host = SMTPServe;
            smtp.Port = Port;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(From, fromPassword);
            smtp.Timeout = 80000;
        }
        try
        {
            smtp.Send(message);
            //return "Your Email has been sent";
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message);
            //return ex.Message;
        }
    }
}

2-

public static byte[] ConvertStreamToByte(Stream input)
    {
        byte[] buffer = new byte[input.Length];
        //byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

3-

byte[] byteArr = ConvertStreamToByte(FileUpload1.PostedFile.InputStream);
SendHtmlMail(ToEmail, Subject, Body, FileUpload1.FileName, byteArr);


ليست هناك تعليقات:

إرسال تعليق