Beispiel #1
0
        public static bool send(string mailto, string subject, string content, string fileAttach)
        {
            System.Web.Mail.MailMessage oMessage = new System.Web.Mail.MailMessage();
            oMessage.To           = mailto;
            oMessage.From         = "*****@*****.**";
            oMessage.Subject      = subject;
            oMessage.Body         = content;
            oMessage.BodyEncoding = System.Text.Encoding.UTF8;
            oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"]  = 2;
            oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = "tuanbm";
            //dinh kem
            System.Web.Mail.MailAttachment myAttachment = new System.Web.Mail.MailAttachment(fileAttach, System.Web.Mail.MailEncoding.Base64);
            oMessage.Attachments.Add(myAttachment);
            //tren server
            System.Web.Mail.SmtpMail.SmtpServer = "tuanbm";
            //dinh dang
            //oMessage.BodyFormat = System.Web.Mail.MailFormat.Html;

            try
            {
                System.Web.Mail.SmtpMail.Send(oMessage);
                //Console.Write(" Gui email thanh cong : ");
                return(true);
            }
            catch (Exception Ex)
            {
                //Console.Write(" Loi : " + Ex);
                return(false);
            }
        }
Beispiel #2
0
        protected void _btnSend_Click(object sender, EventArgs e)
        {
            // show what happened
            _lblErr.Visible = true;

            try
            {
                // create report file
                string fileName = Page.MapPath("report.rtf");
                _c1wr.Report.RenderToFile(fileName, C1.C1Report.FileFormatEnum.RTF);

                // create message
                System.Web.Mail.MailMessage mm = new System.Web.Mail.MailMessage();
                mm.Subject = "Sales Goal Report";
                mm.From    = "*****@*****.**"; // << must be a valid email
                mm.To      = "*****@*****.**";
                mm.Body    = "Hi Joe. I got the sales goal down. Here's the final report.";

                // attach
                System.Web.Mail.MailAttachment att = new System.Web.Mail.MailAttachment(fileName);
                mm.Attachments.Add(att);

                // and send...
                System.Web.Mail.SmtpMail.Send(mm);
                _lblErr.Text = "** Your report is in the mail!";
            }
            catch (Exception x)
            {
                _lblErr.Text      = "Sorry, failed to send because<br>" + x.Message;
                _lblErr.BackColor = Color.Pink;
            }
        }
Beispiel #3
0
        public bool SendEmail(string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath, string pEmailTo)
        {
            try
            {
                System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                    "smtp.gmail.com");
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                    "465");
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                    "2");
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
                //Use 0 for anonymous
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                    "*****@*****.**");
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                    "espl@notification");
                myMail.Fields.Add
                    ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                    "true");
                myMail.From = "*****@*****.**";//[email protected]
                myMail.To   = pEmailTo;
                //myMail.Cc = "*****@*****.**";
                myMail.Subject    = pSubject;
                myMail.BodyFormat = pFormat;
                myMail.Body       = pBody;
                if (pAttachmentPath.Trim() != "")
                {
                    System.Web.Mail.MailAttachment MyAttachment =
                        new System.Web.Mail.MailAttachment(pAttachmentPath);
                    myMail.Attachments.Add(MyAttachment);
                    myMail.Priority = System.Web.Mail.MailPriority.High;
                }

                System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
                System.Web.Mail.SmtpMail.Send(myMail);
                return(true);
            }
            catch (Exception ex)
            {
                // throw;
                return(false);
            }
            finally
            {
                //SendEMail(KeysGlobal.pGmailEmail, KeysGlobal.pTo, pSubject, pBody, pAttachmentPath);
            }
        }
		/// <summary>This is used from wherever email needs to be sent throughout the program.  If a message must be encrypted, then encrypt it before calling this function.  nameValueCollectionHeaders can be null.</summary>
		private static void SendEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress,NameValueCollection nameValueCollectionHeaders,params AlternateView[] arrayAlternateViews) {
			//No need to check RemotingRole; no call to db.
			if(emailAddress.ServerPort==465) {//implicit
				//uses System.Web.Mail, which is marked as deprecated, but still supports implicit
				System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",emailAddress.SMTPserver);
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");//sendusing: cdoSendUsingPort, value 2, for sending the message using the network.
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");//0=anonymous,1=clear text auth,2=context
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",emailAddress.EmailUsername.Trim());
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",emailAddress.EmailPassword);
				//if(PrefC.GetBool(PrefName.EmailUseSSL)) {
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");//false was also tested and does not work
				message.From=emailMessage.FromAddress.Trim();
				message.To=emailMessage.ToAddress.Trim();
				message.Subject=Tidy(emailMessage.Subject);
				message.Body=Tidy(emailMessage.BodyText);
				//message.Cc=;
				//message.Bcc=;
				//message.UrlContentBase=;
				//message.UrlContentLocation=;
				message.BodyEncoding=System.Text.Encoding.UTF8;
				message.BodyFormat=System.Web.Mail.MailFormat.Text;//or .Html
				if(nameValueCollectionHeaders!=null) {
					string[] arrayHeaderKeys=nameValueCollectionHeaders.AllKeys;
					for(int i=0;i<arrayHeaderKeys.Length;i++) {//Needed for Direct Acks to work.
						message.Headers.Add(arrayHeaderKeys[i],nameValueCollectionHeaders[arrayHeaderKeys[i]]);
					}
				}
				//TODO: We need to add some kind of alternatve view or similar replacement for outgoing Direct messages to work with SSL. Write the body to a temporary file and attach with the correct mime type and name?
				string attachPath=EmailMessages.GetEmailAttachPath();
				System.Web.Mail.MailAttachment attach;
				//foreach (string sSubstr in sAttach.Split(delim)){
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new System.Web.Mail.MailAttachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//no way to set displayed filename
					message.Attachments.Add(attach);
				}
				System.Web.Mail.SmtpMail.SmtpServer=emailAddress.SMTPserver+":465";//"smtp.gmail.com:465";
				System.Web.Mail.SmtpMail.Send(message);
			}
			else {//explicit default port 587 
				SmtpClient client=new SmtpClient(emailAddress.SMTPserver,emailAddress.ServerPort);
				//The default credentials are not used by default, according to: 
				//http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx
				client.Credentials=new NetworkCredential(emailAddress.EmailUsername.Trim(),emailAddress.EmailPassword);
				client.DeliveryMethod=SmtpDeliveryMethod.Network;
				client.EnableSsl=emailAddress.UseSSL;
				client.Timeout=180000;//3 minutes
				MailMessage message=new MailMessage();
				message.From=new MailAddress(emailMessage.FromAddress.Trim());
				message.To.Add(emailMessage.ToAddress.Trim());
				message.Subject=Tidy(emailMessage.Subject);
				message.Body=Tidy(emailMessage.BodyText);
				message.IsBodyHtml=false;
				if(nameValueCollectionHeaders!=null) {
					message.Headers.Add(nameValueCollectionHeaders);//Needed for Direct Acks to work.
				}
				for(int i=0;i<arrayAlternateViews.Length;i++) {//Needed for Direct messages to be interpreted encrypted on the receiver's end.
					message.AlternateViews.Add(arrayAlternateViews[i]);
				}
				string attachPath=EmailMessages.GetEmailAttachPath();
				Attachment attach;
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new Attachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//@"C:\OpenDentalData\EmailAttachments\1");
					attach.Name=emailMessage.Attachments[i].DisplayedFileName;
					//"canadian.gif";
					message.Attachments.Add(attach);
				}
				client.Send(message);
			}
		}
Beispiel #5
0
		///////////////////////////////////////////////////////////////////////
		public static string send_email(
			string to,
			string from,
			string cc,
			string subject,
			string body,
			System.Web.Mail.MailFormat body_format,
			System.Web.Mail.MailPriority priority,
			int[] attachment_bpids,
			bool return_receipt)
		{
            Dictionary<string,int> files_to_delete = new Dictionary<string,int>();
			ArrayList directories_to_delete = new ArrayList();
			System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();
			msg.To = to;
			msg.From = from;

            if (!string.IsNullOrEmpty(cc.Trim())) 
            {
                msg.Cc = cc; 
            }
			
            msg.Subject = subject;
			msg.Priority = priority;

			// This fixes a bug for a couple people, but make it configurable, just in case.
			if (Util.get_setting("BodyEncodingUTF8", "1") == "1")
			{
				msg.BodyEncoding = Encoding.UTF8;
			}


			if (return_receipt)
			{
                msg.Headers.Add("Disposition-Notification-To", from);
			}

			// workaround for a bug I don't understand...
			if (Util.get_setting("SmtpForceReplaceOfBareLineFeeds", "0") == "1")
			{
				body = body.Replace("\n", "\r\n");
			}

            msg.Body = body;
			msg.BodyFormat = body_format;


			string smtp_server = Util.get_setting("SmtpServer", "");
			if (smtp_server != "")
			{
				System.Web.Mail.SmtpMail.SmtpServer = smtp_server;
			}

			string smtp_password = Util.get_setting("SmtpServerAuthenticatePassword", "");

			if (smtp_password != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = smtp_password;
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] =
					Util.get_setting("SmtpServerAuthenticateUser", "");
			}

			string smtp_pickup = Util.get_setting("SmtpServerPickupDirectory", "");
			if (smtp_pickup != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory"] = smtp_pickup;
			}


			string send_using = Util.get_setting("SmtpSendUsing", "");
			if (send_using != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = send_using;
			}


			string smtp_use_ssl = Util.get_setting("SmtpUseSSL", "");
			if (smtp_use_ssl == "1")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";
			}

			string smtp_server_port = Util.get_setting("SmtpServerPort", "");
			if (smtp_server_port != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = smtp_server_port;
			}

			if (attachment_bpids != null && attachment_bpids.Length > 0)
			{

				string upload_folder = btnet.Util.get_upload_folder();

				if (string.IsNullOrEmpty(upload_folder))
				{
					upload_folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
					Directory.CreateDirectory(upload_folder);
					directories_to_delete.Add(upload_folder);
				}


				foreach (int attachment_bpid in attachment_bpids)
				{
					byte[] buffer = new byte[16 * 1024];
					string dest_path_and_filename;
					Bug.BugPostAttachment bpa = Bug.get_bug_post_attachment(attachment_bpid);
					using (bpa.content)
					{
						dest_path_and_filename = Path.Combine(upload_folder, bpa.file);

                        // logic to rename in case of dupes.  MS Outlook embeds images all with the same filename
                        int suffix = 0;
                        string renamed_to_prevent_dupe = dest_path_and_filename;
                        while (files_to_delete.ContainsKey(renamed_to_prevent_dupe))
                        {
                            suffix++;
                            renamed_to_prevent_dupe = dest_path_and_filename + Convert.ToString(suffix);
                        }
                        dest_path_and_filename = renamed_to_prevent_dupe;

                        // Save to disk
						using (FileStream out_stream = new FileStream(
							dest_path_and_filename,
							FileMode.CreateNew,
							FileAccess.Write,
							FileShare.None))
						{
                            int bytes_read = bpa.content.Read(buffer, 0, buffer.Length);
							while (bytes_read != 0)
							{
								out_stream.Write(buffer, 0, bytes_read);

								bytes_read = bpa.content.Read(buffer, 0, buffer.Length);
							}
						}

					}

                    // Add saved file as attachment
					System.Web.Mail.MailAttachment mail_attachment = new System.Web.Mail.MailAttachment(
						dest_path_and_filename,
						System.Web.Mail.MailEncoding.Base64);
					msg.Attachments.Add(mail_attachment);
                    files_to_delete[dest_path_and_filename] = 1;
				}
			}


			try
			{
                // This fixes a bug for some people.  Not sure how it happens....
                msg.Body = msg.Body.Replace(Convert.ToChar(0), ' ').Trim();
                System.Web.Mail.SmtpMail.Send(msg);

				// We delete late here because testing showed that SmtpMail class
				// got confused when we deleted too soon.
				foreach (string file in files_to_delete.Keys)
				{
					File.Delete(file);
				}

				foreach (string directory in directories_to_delete)
				{
					Directory.Delete(directory);
				}

				return "";
			}
			catch (Exception e)
			{
				Util.write_to_log("There was a problem sending email.   Check settings in Web.config.");
				Util.write_to_log("TO:" + to);
				Util.write_to_log("FROM:" + from);
				Util.write_to_log("SUBJECT:" + subject);
				Util.write_to_log(e.GetBaseException().Message.ToString());
				return (e.GetBaseException().Message);
			}

		}
Beispiel #6
0
        public static bool SendToUsers(List <string> users, Template template, params string[] attachmentFiles)
        {
            SmtpClient client = new SmtpClient();


            System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
            //sendusing: cdoSendUsingPort, value 2, for sending the message using
            //the network.
            //smtpauthenticate: Specifies the mechanism used when authenticating
            //to an SMTP
            //service over the network. Possible values are:
            //- cdoAnonymous, value 0. Do not authenticate.
            //- cdoBasic, value 1. Use basic clear-text authentication.
            //When using this option you have to provide the user name and password
            //through the sendusername and sendpassword fields.
            //- cdoNTLM, value 2. The current process security context is used to
            // authenticate with the service.
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "*****@*****.**");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "angelo");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            message.From = "*****@*****.**";

            string toUsers = "";

            foreach (string user in users)
            {
                toUsers += user + ";";
            }


            message.Bcc = "*****@*****.**";

            message.To = toUsers;
            //message.Subject = "teste";
            message.BodyFormat = System.Web.Mail.MailFormat.Html;
            //message.Body = "BODY";
            //if ("".Trim() != "")
            //{
            //    MailAttachment MyAttachment = new MailAttachment(pAttachmentPath);
            //    myMail.Attachments.Add(MyAttachment);
            //    myMail.Priority = System.Web.Mail.MailPriority.High;
            //}


            if (attachmentFiles != null && attachmentFiles.Length > 0)
            {
                for (int c = 0; c < attachmentFiles.Length; c++)
                {
                    System.Web.Mail.MailAttachment attach = new System.Web.Mail.MailAttachment(attachmentFiles[c]);
                    message.Attachments.Add(attach);


                    //message.Attachments.Add(new System.Web.Mail.MailAttachment(attachmentFiles[c]));
                }
            }



            //message.To.Add(user.Email);


            switch (template)
            {
            case Template.Welcome:
                message.Subject = "Welcome";
                break;

            case Template.Activation:
                message.Subject = "Activation";
                break;

            case Template.ResetPassword:
                message.Subject = "Reset Password";
                break;

            case Template.ApostasBolao:
                message.Subject = "Apostas dos Usuários";
                break;

            case Template.ApostasRestantes:
                message.Subject = "Apostas restantes";
                break;

            case Template.PagamentosRestantes:
                message.Subject = "Pagamento não efetuado";
                break;
            }//end switch

            //message.IsBodyHtml = true;
            message.Body = LoadTemplates(template);
            message.Body = SetVariables(new Framework.Security.Model.UserData(), message.Body);


            string sslValue = System.Configuration.ConfigurationManager.AppSettings["MailEnableSSL"];

            if (!string.IsNullOrEmpty(sslValue))
            {
                try
                {
                    bool ssl = Convert.ToBoolean(sslValue);
                    client.EnableSsl = ssl;
                }
                catch
                {
                }
            }



            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(message);



            //client.Send(message);


            return(true);
        }
Beispiel #7
0
		///<summary>Throws exceptions.  Attempts to physically send the message over the network wire.
		///This is used from wherever email needs to be sent throughout the program.  If a message must be encrypted, then encrypt it before calling this function.  nameValueCollectionHeaders can be null.</summary>
		private static void WireEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress,NameValueCollection nameValueCollectionHeaders,params AlternateView[] arrayAlternateViews) {
			//No need to check RemotingRole; no call to db.
			//When batch email operations are performed, we sometimes do this check further up in the UI.  This check is here to as a catch-all.
			if(!Security.IsAuthorized(Permissions.EmailSend,DateTime.Now,true,Security.CurUser.UserGroupNum)){//This overload throws an exception if user is not authorized.
				return;
			}
			if(emailAddress.ServerPort==465) {//implicit
				//uses System.Web.Mail, which is marked as deprecated, but still supports implicit
				//http://msdn.microsoft.com/en-us/library/ms877952(v=exchg.65).aspx
				System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",emailAddress.SMTPserver);
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");//sendusing: 1=pickup, 2=port, 3=using microsoft exchange
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");//0=anonymous,1=clear text auth,2=context (NTLM)
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",emailAddress.EmailUsername.Trim());
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",emailAddress.EmailPassword);
				//if(PrefC.GetBool(PrefName.EmailUseSSL)) {
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");//false was also tested and does not work
				message.From=emailMessage.FromAddress.Trim();
				message.To=emailMessage.ToAddress.Trim();
				message.Subject=SubjectTidy(emailMessage.Subject);
				message.Body=BodyTidy(emailMessage.BodyText);
				//message.Cc=;
				//message.Bcc=;
				//message.UrlContentBase=;
				//message.UrlContentLocation=;
				message.BodyEncoding=System.Text.Encoding.UTF8;
				message.BodyFormat=System.Web.Mail.MailFormat.Text;//or .Html
				if(nameValueCollectionHeaders!=null) {
					string[] arrayHeaderKeys=nameValueCollectionHeaders.AllKeys;
					for(int i=0;i<arrayHeaderKeys.Length;i++) {//Needed for Direct Acks to work.
						message.Headers.Add(arrayHeaderKeys[i],nameValueCollectionHeaders[arrayHeaderKeys[i]]);
					}
				}
				//TODO: We need to add some kind of alternatve view or similar replacement for outgoing Direct messages to work with SSL. Write the body to a temporary file and attach with the correct mime type and name?
				string attachPath=EmailAttaches.GetAttachPath();
				System.Web.Mail.MailAttachment attach;
				//foreach (string sSubstr in sAttach.Split(delim)){
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new System.Web.Mail.MailAttachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//No way to set displayed filename on the MailAttachment object itself.  TODO: Copy the file to the temp directory in order to rename, then the attachment will go out with the correct name.
					message.Attachments.Add(attach);
				}
				System.Web.Mail.SmtpMail.SmtpServer=emailAddress.SMTPserver+":465";//"smtp.gmail.com:465";
				System.Web.Mail.SmtpMail.Send(message);
			}
			else {//explicit default port 587 
				SmtpClient client=new SmtpClient(emailAddress.SMTPserver,emailAddress.ServerPort);
				//The default credentials are not used by default, according to: 
				//http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx
				client.Credentials=new NetworkCredential(emailAddress.EmailUsername.Trim(),emailAddress.EmailPassword);
				client.DeliveryMethod=SmtpDeliveryMethod.Network;
				client.EnableSsl=emailAddress.UseSSL;
				client.Timeout=180000;//3 minutes
				MailMessage message=new MailMessage();
				message.From=new MailAddress(emailMessage.FromAddress.Trim());
				message.To.Add(emailMessage.ToAddress.Trim());
				message.Subject=SubjectTidy(emailMessage.Subject);
				message.Body=BodyTidy(emailMessage.BodyText);
				message.IsBodyHtml=false;
				if(nameValueCollectionHeaders!=null) {
					message.Headers.Add(nameValueCollectionHeaders);//Needed for Direct Acks to work.
				}
				for(int i=0;i<arrayAlternateViews.Length;i++) {//Needed for Direct messages to be interpreted encrypted on the receiver's end.
					message.AlternateViews.Add(arrayAlternateViews[i]);
				}
				string attachPath=EmailAttaches.GetAttachPath();
				Attachment attach;
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new Attachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//@"C:\OpenDentalData\EmailAttachments\1");
					attach.Name=emailMessage.Attachments[i].DisplayedFileName;
					//"canadian.gif";
					message.Attachments.Add(attach);
				}
				client.Send(message);
				SecurityLogs.MakeLogEntry(Permissions.EmailSend,emailMessage.PatNum,"Email Sent");
			}
		}
Beispiel #8
0
        public string Send()
        {
            string sTmp;

            System.Web.Mail.MailMessage    objMailMsg;
            System.Web.Mail.MailAttachment objAttachment;

            try
            {
                //m_sBody = ""
                //m_sSubject = ""
                //m_sServer = ""
                //m_iPort = -1
                //m_iTimeOut = 30
                objMailMsg = new System.Web.Mail.MailMessage();
                if (m_sSenderName != "")
                {
                    objMailMsg.From = string.Concat(m_sSenderName, " <", m_sSender, ">");
                }
                else
                {
                    objMailMsg.From = m_sSender;
                }

                if (m_sRecipientName != "")
                {
                    objMailMsg.To = string.Concat(m_sRecipientName, " <", m_sRecipient, ">");
                }
                else
                {
                    objMailMsg.To = m_sRecipient;
                }

                foreach (TRecipient objCC in m_colCC.Values)
                {
                    if (objCC.bBlind)
                    {
                        sTmp = objMailMsg.Bcc;

                        if (sTmp != null)
                        {
                            sTmp = string.Concat(sTmp, "; ");
                        }

                        if (objCC.strName != "")
                        {
                            sTmp = string.Concat(sTmp, objCC.strName, " <", objCC.strEMail, ">");
                        }
                        else
                        {
                            sTmp = string.Concat(sTmp, objCC.strEMail);
                        }

                        objMailMsg.Bcc = sTmp;
                        sTmp           = "";
                    }
                    else
                    {
                        sTmp = objMailMsg.Cc;
                        if (sTmp != null)
                        {
                            sTmp = string.Concat(sTmp, "; ");
                        }

                        if (objCC.strName != "")
                        {
                            sTmp = string.Concat(sTmp, objCC.strName, " <", objCC.strEMail, ">");
                        }
                        else
                        {
                            sTmp = string.Concat(sTmp, objCC.strEMail);
                        }

                        objMailMsg.Cc = sTmp;
                        sTmp          = "";
                    }
                }

                objMailMsg.Subject = m_sSubject;
                objMailMsg.Body    = m_sBody;

                foreach (string sFilename in m_colAttachments.Values)
                {
                    objAttachment = new System.Web.Mail.MailAttachment(sFilename);
                    objMailMsg.Attachments.Add(objAttachment);
                    objAttachment = null;
                }

                System.Web.Mail.SmtpMail.SmtpServer = m_sServer;

                switch (m_iBodyFormat)
                {
                case TEnumBodyFormat.HTML:
                    objMailMsg.BodyFormat = System.Web.Mail.MailFormat.Html;
                    break;

                case TEnumBodyFormat.PlainText:
                    objMailMsg.BodyFormat = System.Web.Mail.MailFormat.Text;
                    break;
                }

                switch (m_iPriority)
                {
                case TEnumPriority.NORMAL:
                    objMailMsg.Priority = System.Web.Mail.MailPriority.Normal;
                    break;

                case TEnumPriority.HIGH:
                    objMailMsg.Priority = System.Web.Mail.MailPriority.High;
                    break;

                case TEnumPriority.LOW:
                    objMailMsg.Priority = System.Web.Mail.MailPriority.Low;
                    break;
                }

                System.Web.Mail.SmtpMail.Send(objMailMsg);
                return("OK");
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
            finally
            {
                objMailMsg = null;
            }
        }
Beispiel #9
0
        /// <summary>
        /// 同步发送邮件
        /// </summary>
        /// <param name="to">收件人邮箱地址(多个用英文,或;分割)</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="attachmentPaths">附件路径</param>
        /// <param name="encoding">编码</param>
        /// <param name="isBodyHtml">是否Html</param>
        /// <returns>是否成功</returns>
        public static bool Send(string to, string subject, string body, string attachmentPaths = null, string encoding = "UTF-8", bool isBodyHtml = true)
        {
            var result = false;

            if (!string.IsNullOrEmpty(to))
            {
                try
                {
                    if (BaseSystemInfo.MailServerSslEnabled && BaseSystemInfo.MailServerPort == 465)
                    {
#if NET40_OR_GREATER
                        var message = new System.Web.Mail.MailMessage();
                        //接收人邮箱地址
                        message.To = to;

                        if (!string.IsNullOrEmpty(BaseSystemInfo.MailBcc))
                        {
                            message.Bcc = BaseSystemInfo.MailBcc;
                        }

                        if (!string.IsNullOrEmpty(BaseSystemInfo.MailFrom))
                        {
                            message.From = BaseSystemInfo.MailFrom;
                        }

                        //在有附件的情况下添加附件
                        if (!string.IsNullOrEmpty(attachmentPaths))
                        {
                            message.Attachments.Clear();
                            try
                            {
                                string[] attachPath = attachmentPaths.Split(';');
                                System.Web.Mail.MailAttachment attachFile = null;
                                foreach (string path in attachPath)
                                {
                                    //string extName = Path.GetExtension(path).ToLower(); //获取扩展名
                                    //FileStream fs = new FileStream(HostingEnvironment.MapPath("/") + pathFileName, FileMode.Open, FileAccess.Read);
                                    ////将附件添加到mailmessage对象
                                    //attachment = new Attachment(fs, dictionary[i]);
                                    attachFile = new System.Web.Mail.MailAttachment(path);
                                    message.Attachments.Add(attachFile);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogUtil.WriteException(ex);
                            }
                        }
                        message.BodyEncoding = Encoding.GetEncoding(encoding);
                        message.Body         = body;
                        message.Subject      = subject;
                        if (isBodyHtml)
                        {
                            message.BodyFormat = System.Web.Mail.MailFormat.Html;
                        }

                        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
                        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", BaseSystemInfo.MailUserName);
                        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", BaseSystemInfo.MailPassword);
                        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", BaseSystemInfo.MailServerPort);//端口
                        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", BaseSystemInfo.MailServerSslEnabled);

                        System.Web.Mail.SmtpMail.SmtpServer = BaseSystemInfo.MailServer;
                        System.Web.Mail.SmtpMail.Send(message);
#endif
                    }
                    else
                    {
                        var message = new MailMessage();
                        //接收人邮箱地址
                        if (!to.Contains(",") && !to.Contains(";"))
                        {
                            message.To.Add(new MailAddress(to));
                        }
                        else if (!string.IsNullOrWhiteSpace(to))
                        {
                            string[] tos = null;
                            if (to.Contains(","))
                            {
                                tos = to.Split(",".ToCharArray());
                            }
                            else if (to.Contains(";"))
                            {
                                tos = to.Split(";".ToCharArray());
                            }

                            foreach (var t in tos)
                            {
                                message.To.Add(new MailAddress(t));
                            }
                        }

                        if (!string.IsNullOrEmpty(BaseSystemInfo.MailBcc))
                        {
                            message.Bcc.Add(new MailAddress(BaseSystemInfo.MailBcc));
                        }

                        if (!string.IsNullOrEmpty(BaseSystemInfo.MailFrom))
                        {
                            message.From = new MailAddress(BaseSystemInfo.MailFrom);
                        }

                        //在有附件的情况下添加附件
                        if (!string.IsNullOrEmpty(attachmentPaths))
                        {
                            message.Attachments.Clear();
                            try
                            {
                                string[]   attachPath = attachmentPaths.Split(';');
                                Attachment attachFile = null;
                                foreach (string path in attachPath)
                                {
                                    //string extName = Path.GetExtension(path).ToLower(); //获取扩展名
                                    //FileStream fs = new FileStream(HostingEnvironment.MapPath("/") + pathFileName, FileMode.Open, FileAccess.Read);
                                    ////将附件添加到mailmessage对象
                                    //attachment = new Attachment(fs, dictionary[i]);
                                    attachFile = new Attachment(path);
                                    message.Attachments.Add(attachFile);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogUtil.WriteException(ex);
                            }
                        }
                        message.BodyEncoding    = Encoding.GetEncoding(encoding);
                        message.Body            = body;
                        message.SubjectEncoding = Encoding.GetEncoding(encoding);
                        message.Subject         = subject;
                        message.IsBodyHtml      = isBodyHtml;

                        var smtpClient = new SmtpClient(BaseSystemInfo.MailServer, BaseSystemInfo.MailServerPort)
                        {
                            Credentials = new NetworkCredential(BaseSystemInfo.MailUserName, BaseSystemInfo.MailPassword),
                            //SSL设置
                            EnableSsl = BaseSystemInfo.MailServerSslEnabled
                        };

                        smtpClient.Send(message);
                    }

                    result = true;
                }
#if NET40_OR_GREATER
                catch (System.Web.HttpException ex)
                {
                    LogUtil.WriteException(ex);
                }
#endif
                catch (SmtpException ex)
                {
                    LogUtil.WriteException(ex);
                }
                catch (Exception ex)
                {
                    LogUtil.WriteException(ex);
                }
            }

            return(result);
        }