Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

My issue is this that I am trying to make use email sending task at my website for the admin person.

When he selects the email ids from the available data and attach a attachment and than sends email, email is never recieved by user, however if he is using simple mailing ie. without any attachment, user gets it.

Can u help please ?

My coding is given below :-


C#
public partial class SahibAdmin_emailNewsletter : System.Web.UI.Page
{

    //DataService ds = new DataService();
    SahibImportDataService ds = new SahibImportDataService();
    string Uname;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["msg"] == "sent")
        {

            TD1.InnerHtml = "Newsletters Are Sent Successfully";
        }
        if (!Page.IsPostBack)
        {
            string sqlEmail = "Select * from TBL_User order by Company_name";
            DataTable dtEmailId = ds.data_SelectByAdap(sqlEmail);
            gvEmail.DataSource = dtEmailId;
            gvEmail.DataBind();
        }

    }
    protected void btnSendNews_Click(object sender, EventArgs e)
    {
        string strLogin = "select fname,lname,emailid from TBL_User where emailid = 'xyz@gmail.com' ";
        SqlDataReader sdrLogin = ds.data_Select(strLogin);
        while (sdrLogin.Read())
        {
            Uname = sdrLogin.GetString(sdrLogin.GetOrdinal("fName")) + " " + sdrLogin.GetString(sdrLogin.GetOrdinal("lName"));
        }

        //lblMsg.Text = "Welcome, " + Uname;
        sdrLogin.Close();

        try
        {
            fetchEmailId();
            Response.Redirect("emailNewsletter.aspx?msg=sent");
        }
        catch (Exception ex)
        {
            TD1.InnerHtml = "";
            TD1.InnerHtml = "ERROR: " + ex.Message.ToString();

        }
       
    }
    private void fetchEmailId()
    {int count = 0;
        string strUser = "";
        for (int i = 0; i < gvEmail.Rows.Count; i++)
        {
            if (((CheckBox)(gvEmail.Rows[i].FindControl("check"))).Checked == true)
            {
                count = count + 1;
                status_msg.Visible = false;
            }
           
        }
        if (count >= 1)
        {
            for (int i = 0; i < gvEmail.Rows.Count; i++)
            {
                if (((CheckBox)(gvEmail.Rows[i].FindControl("check"))).Checked == true)
                {
                    strUser += ((Label)(gvEmail.Rows[i].FindControl("emailid"))).Text + ",";
                   
                }
                  
            }
            strUser = strUser.Remove((strUser.Length - 1));
            SendNewsletter(strUser);
        }
        else
        {
            count = 0;
            status_msg.Text = "Please select email ids to send newsletter";
            status_msg.Visible = true;
        }
       
    }
    protected void gvEmail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int rowno = e.Row.DataItemIndex + 1;
            e.Row.Cells[1].Text = rowno.ToString();
          //  e.Row.Cells[1].CssClass = "msgGreen11";
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
        }
    }
    private void SendNewsletter(string emailId)
    {
       

        System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
        message.To = emailId;
        message.From = "info@sahibimports.com";
        message.Subject = "Please See: Newsletter from Sahib imports";
        message.BodyFormat = System.Web.Mail.MailFormat.Text;
        message.Body = txtBody.Text.ToString();
        if (msgUpload.HasFile)
        {
            //string strFileName = msgUpload.FileName;
            //msgUpload.PostedFile.SaveAs(Server.MapPath(strFileName));
            //System.Web.Mail.MailAttachment attach = new System.Web.Mail.MailAttachment(Server.MapPath(strFileName));
            //message.Attachments.Add(attach);

            message.Attachments.Add(new Attachment(FileUpload.PostedFile.InputStream, FileUpload.FileName));

        }
        System.Web.Mail.SmtpMail.Send(message);
        Response.Flush();

    }
}
Posted
Updated 14-Feb-12 19:27pm
v2
Comments
Manfred Rudolf Bihy 15-Feb-12 1:28am    
Unchecked checkbox "Treat my content as plain text, not as HTML", so that the pre tags are properly formatted.

Hi,

Try this...

Example:
In Web.Config file:

C#
<appsettings>
  <add key="EmailTo" value="YourEmail@live.com.ph;MayEmail@live.com;" />
  <add key="EmailCc" value="CcEmal@live.com;" />
  <add key="EmailFrom" value="Me@live.com" />
  <add key="SMTP_Address" value="192.123.456.7" />
 </appsettings>



In code behind:
C#
string strSubject = "Test Email with Attachment";
string strMessage = "Testing Feedback email only by Algem Mojedo";
string strContact = "MyContact@live.com";
string strAttachments = "C:\\Documents and Settings\\agm\\Desktop\\sqlnet.log";
var sResult = EmailHandler.SendEmailFeedback(strSubject, strMessage,  strContact, strAttachments);


C#
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using System.Globalization;
using System.Configuration;
using System.Net.Mail;

public static class EmailHandler
{
    public static string SendEmailFeedback(string subject, string message, string contact, string attachment)
    {
        string strEmailResult = string.Empty;
        string strEmailFrom = string.Empty;
        string strEmailTo = string.Empty;
        string strEmailCc = string.Empty;
        string strEmailSMTP = string.Empty;

        strEmailFrom = ConfigurationSettings.AppSettings["EmailFrom"].ToString();
        strEmailTo = ConfigurationSettings.AppSettings["EmailTo"].ToString();
        strEmailCc = ConfigurationSettings.AppSettings["EmailCc"].ToString();
        strEmailSMTP = ConfigurationSettings.AppSettings["SMTP_Address"].ToString();

        try
        {
            System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage();
            SmtpClient mailClient = new SmtpClient(strEmailSMTP);
            emailMessage.Priority = System.Net.Mail.MailPriority.High;
            emailMessage.From = new MailAddress(strEmailFrom);
            emailMessage.Subject = subject;
            emailMessage.Body = message;
            emailMessage.IsBodyHtml = true;


            if ((strEmailTo.Contains("@")) && (strEmailTo.Length > 4))
            {
                int count = CountStringOccurrences(strEmailTo, ";");

                for (int i = 0; i < count; i++)
                {
                    string strToRecieptient = strEmailTo.Split(';')[i].ToString();
                    emailMessage.To.Add(strToRecieptient);
                }

            }

            if (strEmailCc != string.Empty)
            {
                if ((strEmailCc.Contains("@")) && (strEmailCc.Length > 4))
                {
                    int icount = CountStringOccurrences(strEmailCc, ";");

                    for (int i = 0; i < icount; i++)
                    {
                        string strCCrecipient = strEmailCc.Split(';')[i].ToString();
                        emailMessage.Bcc.Add(strCCrecipient);
                    }
                }
            }
            foreach (string strAttachment in attachment.Split(';'))
            {
                System.Net.Mail.Attachment objAttachment = new System.Net.Mail.Attachment(strAttachment);
                emailMessage.Attachments.Add(objAttachment);
            }

            mailClient.Send(emailMessage);

            strEmailResult = "Message was successfully sent to the System Administrator.";
        }
        catch (Exception ex)
        {
            strEmailResult = ex.Message.ToString() + "; error";   
        }

        return strEmailResult;
    }

    private static int CountStringOccurrences(string text, string pattern)
    {
        // Loop through all instances of the string 'text'.
        int count = 0;
        int i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
        {
            i += pattern.Length;
            count++;
        }
        return count;
    }
}



Please vote if could help so that other may consider as an answer...
 
Share this answer
 
v2
Comments
zyck 15-Feb-12 4:41am    
5up
Hi,

below mail function will be useful to you
C#
public static bool SendMailWithAttechment(string strFrom, string strTo, string strCC, string strBCC, string strSubject, string strBody, string strAttachments)
      {
      /*******************************
          This mail function is based on web mail so you need to add
          using System.Web.Mail;
      *******************************/
          try
          {

              MailMessage MyMail = new MailMessage();

              MyMail.From = strFrom;

              if (strTo.IndexOf(',') >= 0)
              {
                  strTo = strTo.Replace(',', ';');
              }

              MyMail.To = strTo;


              if (strCC != "")
              {
                  Split CC Address
                  if (strCC.IndexOf(',') >= 0)
                  {
                      strCC = strCC.Replace(',', ';');
                  }

                  MyMail.Cc = strCC;
              }

              if (strBCC != "")
              {
                  if (strBCC.IndexOf(',') >= 0)
                  {
                      strBCC = strBCC.Replace(',', ';');
                  }

                  MyMail.Bcc = strBCC;
              }
              foreach (string strAttachment in strAttachments.Split(';'))
              {
                  MailAttachment objAttachment = new MailAttachment(strAttachment);
                  MyMail.Attachments.Add(objAttachment);
              }
              MyMail.Subject = strSubject;
              MyMail.Body = strBody;

              MyMail.BodyFormat = MailFormat.Html;
              SmtpMail.SmtpServer = "localhost";
              SmtpMail.Send(MyMail);

          }
          catch (Exception objerr)
          {
              //set error message for mail
              return false;
          }

          return true;

      }
 
Share this answer
 
use this,

C#
public static bool sendEmail(string strSubject, string strFrom, string strTo, string strBody, string strCc, string strBcc, string displayName)
    {
        System.Net.Mail.SmtpClient Mail = new System.Net.Mail.SmtpClient();
        Mail.Host = ConfigurationManager.AppSettings["SMTPServer"].ToString();


        string username = null;
        string Password = null;
        if (ConfigurationManager.AppSettings["UseDefaultCredentials"] + "" == "false")
        {
            Mail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            username = ConfigurationManager.AppSettings["MailUserName"];
            Password = ConfigurationManager.AppSettings["MailPassword"];
            System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(username, Password);
            if ((ConfigurationManager.AppSettings["MailPort"] != null) && (isNumeric(ConfigurationManager.AppSettings["MailPort"])))
            {
                Mail.Port = Convert.ToInt16(ConfigurationManager.AppSettings["MailPort"]);
            }
            Mail.UseDefaultCredentials = false;
            Mail.Credentials = basicAuthenticationInfo;
            if (ConfigurationManager.AppSettings["EnableSsl"] == "True")
                Mail.EnableSsl = true;
            
        }

        System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();
        myMail.Subject = strSubject;
        string strFileName = msgUpload.FileName;
        msgUpload.PostedFile.SaveAs(Server.MapPath(strFileName));
        System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(Server.MapPath(strFileName));
        myMail.Attachments.Add(attach);

        myMail.From = new System.Net.Mail.MailAddress(strFrom, displayName);
        myMail.To.Add(new System.Net.Mail.MailAddress(strTo));          

        myMail.IsBodyHtml = true;
        myMail.Body = strBody;
        try
        {            
            Mail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            return false;
        }
    }


Hope this may help you...
And Don't forget to mark as answer if it helps. :)
 
Share this answer
 
v2
Hi,

I am getting this error when i try to send a email with attachment in my code which i have shown in the top.

<b>ERROR: The "SendUsing" configuration value is invalid.</b>
Pls help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900