无法发送带有附件的电子邮件. [英] Unable to send E-mail with attachment.

查看:79
本文介绍了无法发送带有附件的电子邮件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的问题是我试图在管理员的网站上使用电子邮件发送任务.

当他从可用数据中选择电子邮件ID并附加附件并发送电子邮件时,用户将永远不会收到电子邮件,但是,如果他使用的是简单邮件,即.没有任何附件,用户即可获取.

你能帮忙吗?

我的编码如下:-


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 :-


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();

    }
}

推荐答案



试试这个...

示例:
在Web.Config文件中:

Hi,

Try this...

Example:
In Web.Config file:

<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:

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);





 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...


您好,

下面的邮件功能对您很有用
Hi,

below mail function will be useful to you
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;

      }


使用此功能,

use this,

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. :)


这篇关于无法发送带有附件的电子邮件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆