Ejemplo n.º 1
0
        /// <summary>
        /// Used to send mails .... Fetechs credentails used to send mails...
        /// </summary>
        /// <param name="mails"></param>
        /// <param name="AD_User_ID"></param>
        /// <param name="AD_Client_ID"></param>
        /// <param name="AD_Org_ID"></param>
        /// <param name="attachment_ID"></param>
        /// <param name="fileNames"></param>
        /// <param name="fileNameForOpenFormat"></param>
        /// <param name="mailFormat"></param>
        /// <param name="notify"></param>
        /// <returns></returns>
        public string SendMails(List <NewMailMessage> mails, int AD_User_ID, int AD_Client_ID, int AD_Org_ID, int attachment_ID, List <string> fileNames, List <string> fileNameForOpenFormat, string mailFormat, bool notify, List <int> lstDocumentIds)
        {
            VAdvantage.Utility.EMail sendmail = new VAdvantage.Utility.EMail(ctx, "", "", "", "", "", "",
                                                                             true, false);
            string isConfigExist = sendmail.IsConfigurationExist(ctx);

            if (isConfigExist != "OK")
            {
                return(isConfigExist);
            }

            sendmail = null;


            if (notify)//if want to send mail on server and want notice on home screen.     Else u have to wait, and it will show alert message of return value....
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    SendMailstart(mails, AD_User_ID, AD_Client_ID, AD_Org_ID, attachment_ID, fileNames, fileNameForOpenFormat, mailFormat, notify, sendmail, lstDocumentIds);
                });
                return("");
            }
            else
            {
                return(SendMailstart(mails, AD_User_ID, AD_Client_ID, AD_Org_ID, attachment_ID, fileNames, fileNameForOpenFormat, mailFormat, notify, sendmail, lstDocumentIds));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// this method actually send mail, both static and dynamic.... and save info in MailAttachment....
        /// </summary>
        /// <param name="mails"></param>
        /// <param name="AD_User_ID"></param>
        /// <param name="AD_Client_ID"></param>
        /// <param name="AD_Org_ID"></param>
        /// <param name="attachment_ID"></param>
        /// <param name="fileNames"></param>
        /// <param name="fileNameForOpenFormat"></param>
        /// <param name="mailFormat"></param>
        /// <param name="notify"></param>
        /// <returns></returns>
        public string SendMailstart(List <NewMailMessage> mails, int AD_User_ID, int AD_Client_ID, int AD_Org_ID, int attachment_ID, List <string> fileNames, List <string> fileNameForOpenFormat, string mailFormat, bool notify, VAdvantage.Utility.EMail sendmails, List <int> documentID)
        {
            if (ctx == null)
            {
                return(null);
            }


            UserInformation userinfo = new UserInformation();
            SMTPConfig      config   = null;

            config = MailConfigMethod.GetUSmtpConfig(AD_User_ID, ctx);
            // var config = "";
            if (config == null)
            {
                MClient client = new MClient(ctx, AD_Client_ID, null);
                userinfo.Email = client.GetRequestEMail();
            }
            else
            {
                //Add user info to list..
                userinfo.Email = config.Email;
            }

            string[] to = null;
            string[] bc = null;

            string[] cc      = null;
            string   sub     = null;
            string   message = null;
            // int _record_id = 0;
            int _table_id = 0;

            string[] records = null;

            StringBuilder res = new StringBuilder();

            List <NewMailMessage> mail = mails.GetRange(0, mails.Count);

            for (int j = 0; j < mails.Count; j++)
            {
                VAdvantage.Utility.EMail sendmail = new VAdvantage.Utility.EMail(ctx, "", "", "", "", "", "",
                                                                                 true, false);

                to = mails[j].To.Split(';');
                bc = mails[j].Bcc;
                cc = mails[j].Cc.Split(';');
                StringBuilder bcctext = new StringBuilder();
                sub     = mails[j].Subject;
                message = mailFormat;
                if (mails[j].Body != null && mails[j].Body.Count > 0)
                {
                    List <string> keysss = mails[j].Body.Keys.ToList();
                    for (int q = 0; q < keysss.Count; q++)
                    {
                        message = message.Replace(keysss[q], mails[j].Body[keysss[q]]);
                    }
                }

                if (mails[j].Recordids != null)          //in case of static mail
                {
                    records = mails[j].Recordids.Split(',');
                }

                _table_id = Convert.ToInt32(mail[j].TableID);

                VAdvantage.Model.MMailAttachment1 _mAttachment = new VAdvantage.Model.MMailAttachment1(ctx, 0, null);



                if (sub == null || sub.Length == 0 || sub == "")
                {
                    sendmail.SetSubject(".");   //	pass validation
                }
                else
                {
                    sendmail.SetSubject(sub);
                }
                sendmail.SetMessageHTML(message);


                //used to get attachments uploaded by user.....
                if (mail[j].AttachmentFolder != null && mail[j].AttachmentFolder.Trim().Length > 0)
                {
                    string storedAttachmentPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, AttachmentsUploadFolderName + "\\" + mail[j].AttachmentFolder);
                    if (Directory.Exists(storedAttachmentPath))
                    {
                        DirectoryInfo info = new DirectoryInfo(storedAttachmentPath);
                        if (info.GetFiles().Length > 0)
                        {
                            FileInfo[] files = info.GetFiles();

                            for (int a = 0; a < files.Length; a++)
                            {
                                if (fileNames.Contains(files[a].Name))
                                {
                                    FileStream   attachmentStream = File.OpenRead(files[a].FullName);
                                    BinaryReader binary           = new BinaryReader(attachmentStream);
                                    byte[]       buffer           = binary.ReadBytes((int)attachmentStream.Length);
                                    sendmail.AddAttachment(buffer, files[a].Name);
                                    _mAttachment.AddEntry(files[a].Name, buffer);
                                }
                            }
                        }
                    }
                }

                //used to get attachments of saved formats.. Currently not Supporting......
                if (attachment_ID > 0)
                {
                    VAdvantage.Model.MMailAttachment1 _mAttachment1 = new VAdvantage.Model.MMailAttachment1(ctx, attachment_ID, null);
                    if (_mAttachment1.GetEntryCount() > 0)
                    {
                        MAttachmentEntry[] entries = _mAttachment1.GetEntries();
                        for (int m = 0; m < entries.Count(); m++)
                        {
                            //if (fileNameForOpenFormat.Contains(entries[m].GetName()))
                            //{
                            byte[] buffer = entries[m].GetData();
                            sendmail.AddAttachment(buffer, entries[m].GetName());
                            _mAttachment.AddEntry(entries[m].GetName(), buffer);
                            //}
                        }
                    }
                }

                if (documentID != null || documentID.Count > 0)
                {
                    for (int i = 0; i < documentID.Count; i++)
                    {
                        try
                        {
                            int attachmentID = AttachmentID(documentID[i]);
                            //MAttachment objAttachment = new MAttachment(ctx, attachmentID, null, Common.GetPassword(), ctx.GetAD_Client_ID());
                            //objAttachment.Force = false;
                            ////objAttachment.AD_Client_ID = ctx.GetAD_Client_ID();
                            //byte[] fileByte = objAttachment.GetEntryData(0);
                            //string fileName = objAttachment.GetEntryName(0);
                            List <AttachedFileInfo> lstAttchments = GetBytes(ctx, attachmentID, "");
                            sendmail.AddAttachment(lstAttchments[0].FileBytes, lstAttchments[0].FileName);
                        }
                        catch (Exception ex)
                        {
                            res.Append(Msg.GetMsg(ctx, "VADMS_AttachmentNotFound for : " + documentID[i]) + ex.Message);
                        }
                    }
                }



                if (to != null)
                {
                    for (int i = 0; i < to.Length; i++)
                    {
                        if (to[i].ToString() != "")
                        {
                            sendmail.AddTo(to[i].ToString(), "");
                            // totext.Append(to[i].ToString() + ",");
                        }
                    }
                }

                if (bc != null)
                {
                    for (int i = 0; i < bc.Length; i++)
                    {
                        if (bc[i].ToString() != "")
                        {
                            sendmail.AddBcc(bc[i].ToString(), "");
                            bcctext.Append(bc[i].ToString() + ",");
                        }
                    }
                }

                if (cc != null)
                {
                    for (int i = 0; i < cc.Length; i++)
                    {
                        if (cc[i].ToString() != "")
                        {
                            sendmail.AddCc(cc[i].ToString(), "");
                            ///  cctext.Append(cc[i].ToString() + ",");
                        }
                    }
                }

                string res1 = sendmail.Send();

                if (records != null && records.Length > 0)//save entery in MailAttachment......
                {
                    for (int k = 0; k < records.Length; k++)
                    {
                        if (records[k] == null || records[k] == "" || records[k] == "0")
                        {
                            continue;
                        }
                        if (res1 != "OK")
                        {
                            _mAttachment.SetIsMailSent(false);
                        }
                        else
                        {
                            _mAttachment.SetIsMailSent(true);
                        }
                        int AD_Client_Id = ctx.GetAD_Client_ID();
                        int iOrgid       = ctx.GetAD_Org_ID();

                        _mAttachment.SetAD_Client_ID(AD_Client_Id);
                        _mAttachment.SetAD_Org_ID(iOrgid);
                        _mAttachment.SetAD_Table_ID(_table_id);
                        _mAttachment.IsActive();
                        _mAttachment.SetMailAddress(bcctext.ToString());
                        _mAttachment.SetAttachmentType("M");

                        _mAttachment.SetRecord_ID(Convert.ToInt32(records[k]));

                        _mAttachment.SetTextMsg(message);
                        _mAttachment.SetTitle(sub);

                        _mAttachment.SetMailAddressBcc(bcctext.ToString());
                        _mAttachment.SetMailAddress(mails[j].To);
                        _mAttachment.SetMailAddressCc(mails[j].Cc);
                        _mAttachment.SetMailAddressFrom(userinfo.Email);
                        if (_mAttachment.GetEntries().Length > 0)
                        {
                            _mAttachment.SetIsAttachment(true);
                        }
                        else
                        {
                            _mAttachment.SetIsAttachment(false);
                        }
                        _mAttachment.NewRecord();
                        if (_mAttachment.Save())
                        {
                        }
                        else
                        {
                            // log.SaveError(Msg.GetMsg(Env.GetCtx(), "RecordNotSaved"), "");
                        }
                    }
                }

                if (res1 != "OK")           // if mail not sent....
                {
                    if (res1 == "AuthenticationFailed.")
                    {
                        res.Append("AuthenticationFailed");
                        return(res.ToString());
                    }
                    else if (res1 == "ConfigurationIncompleteOrNotFound")
                    {
                        res.Append("ConfigurationIncompleteOrNotFound");
                        return(res.ToString());
                    }
                    else
                    {
                        res.Append(" " + Msg.GetMsg(ctx, "MailNotSentTo") + ": " + mails[j].To + " " + bcctext + " " + mails[j].Cc);
                    }
                }
                else
                {
                    {
                        if (!res.ToString().Contains("MailSent"))
                        {
                            res.Append("MailSent");
                        }
                    }
                }
                bcctext = null;
            }

            if (notify)             //  make an entry in Notice window.....
            {
                MNote note = new MNote(ctx, "SentMailNotice", AD_User_ID,
                                       AD_Client_ID, AD_Org_ID, null);
                //  Reference
                note.SetReference(ToString());  //	Document
                //	Text
                note.SetTextMsg(res.ToString());
                note.Save();
            }

            userinfo = null;
            cc       = null;
            bc       = null;
            to       = null; records = null;
            sub      = null; message = null;
            records  = null;
            return(res.ToString());
        }
        public void SendEmailOrNotification(Ctx ctx, int userID, bool isEmail, bool isNotification, bool isBoth, int tableid, StringBuilder strBuilder, string message, int recordID, string searchKey)
        {
            //******************Temporary Commented******************
            // VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);

            string emailID = Convert.ToString(DB.ExecuteScalar("SELECT EMAIL FROM AD_USER WHERE AD_USER_ID=" + userID));

            message += " (" + searchKey + ")";

            try
            {
                if (isEmail)
                {
                    //  log.Log(Level.SEVERE, "SendOnlyEmailToSubscribeUser");
                    //  VAdvantage.Logging.VLogger.Get().Info("SendOnlyEmailToSubscribeUser");
                    // VAdvantage.Utility.EMail objEmail = new VAdvantage.Utility.EMail(ctx, string.Empty, string.Empty, string.Empty, string.Empty, Msg.GetMsg(ctx, "VADMS_FolderSubscriptionNotification"), message,false,true);
                    VAdvantage.Utility.EMail objEmail = new EMail(ctx, string.Empty, string.Empty, string.Empty, string.Empty, "AttachEmailNotification", message, false, true);
                    if (emailID.IndexOf(";") > -1)
                    {
                        string[] eIDS = emailID.Split(';');

                        for (int k = 0; k < eIDS.Length; k++)
                        {
                            objEmail.AddTo(eIDS[k], "");
                        }
                    }
                    else
                    {
                        objEmail.AddTo(emailID, "");
                    }
                    objEmail.SetMessageText(message);
                    objEmail.SetSubject("AttachEmailNotification");
                    string resu = objEmail.Send();
                }
                else if (isNotification)
                {
                    //  log.Log(Level.SEVERE, "SendOnlyNoticeToSubscribeUser");

                    MNote note = new MNote(ctx, 0, null);
                    note.SetAD_User_ID(userID);
                    // changes done by Bharat on 22 May 2018 to set Organization to * on Notification as discussed with Mukesh Sir.
                    //note.SetClientOrg(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID());
                    note.SetClientOrg(ctx.GetAD_Client_ID(), 0);
                    note.SetTextMsg(message);
                    note.SetDescription(Msg.GetMsg(ctx, "AttachEmailNotification"));
                    note.SetRecord(tableid, recordID); // point to this
                    note.SetAD_Message_ID(859);        //Workflow
                    if (!note.Save())
                    {
                        // CreateMessage(strBuilder, Convert.ToString(recordID));
                    }
                }
                else if (isBoth)
                {
                    // log.Log(Level.SEVERE, "SendOnlyEmailAndNoticeToSubscribeUser");

                    VAdvantage.Utility.EMail objEmail = new VAdvantage.Utility.EMail(ctx, string.Empty, string.Empty, string.Empty, string.Empty, Msg.GetMsg(ctx, "AttachEmailNotification"), message, false, true);
                    // VAdvantage.Utility.EMail objEmail = new EMail(ctx, string.Empty, string.Empty, emailID, string.Empty, Msg.GetMsg(ctx, "VADMS_FolderSubscriptionNotification"), message, false, true);
                    if (emailID.IndexOf(";") > -1)
                    {
                        string[] eIDS = emailID.Split(';');

                        for (int k = 0; k < eIDS.Length; k++)
                        {
                            objEmail.AddTo(eIDS[k], "");
                        }
                    }
                    else
                    {
                        objEmail.AddTo(emailID, "");
                    }
                    objEmail.SetMessageText(message);
                    objEmail.SetSubject(Msg.GetMsg(ctx, "AttachEmailNotification"));
                    objEmail.Send();
                    MNote note = new MNote(ctx, 0, null);
                    note.SetAD_User_ID(userID);
                    // changes done by Bharat on 22 May 2018 to set Organization to * on Notification as discussed with Mukesh Sir.
                    //note.SetClientOrg(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID());
                    note.SetClientOrg(ctx.GetAD_Client_ID(), 0);
                    note.SetTextMsg(message);
                    note.SetDescription(Msg.GetMsg(ctx, "AttachEmailNotification"));
                    note.SetRecord(tableid, recordID); // point to this
                    note.SetAD_Message_ID(859);        //Workflow
                    if (!note.Save())
                    {
                        // CreateMessage(strBuilder, Convert.ToString(recordID));
                    }
                }
            }
            catch (Exception ex)
            {
                VAdvantage.Logging.VLogger.Get().Info(ex.Message);
                log.Severe("SendEmailOrNotification Error : " + ex.Message);
            }

            //***************************************
        }
        private string SendEmailWithAttachment(string Subject, string Message, DataSet ds1, int AD_Org_ID, int Ad_Client_ID)
        {
            string Check = "";
            int    count = 0;
            string res   = "";

            List <string> EmailLst = new List <string>(); //!string.IsNullOrEmpty(EmailIDs) ? EmailIDs.Split(',').ToList() : null;

            int UpdatedBy = GetCtx().GetAD_User_ID();

            sendmail = new VAdvantage.Utility.EMail(GetCtx(), "", "", "", "", "", "", true, false);
            string isConfigExist = sendmail.IsConfigurationExist(GetCtx());

            if (isConfigExist != "OK")
            {
                log.SaveError("Check email configuration", "");
                return(Msg.GetMsg(GetCtx(), "VIS_CheckMailConfig"));
            }

            if (ds1 != null && ds1.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    if (Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "A" ||
                        Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "B" ||
                        Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "E" ||
                        Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "L")
                    {
                        sendmail.AddBcc(Util.GetValueOfString(ds1.Tables[0].Rows[i]["EMAIL"]));
                    }
                }

                sendmail.SetSubject(Subject);
                sendmail.SetMessageText(Message);

                MAttachment mAttach  = GetFileAttachment(GetTable_ID(), GetRecord_ID(), GetCtx());
                string      filePath = "";

                if (mAttach != null && mAttach.AD_Attachment_ID > 0)
                {
                    if (mAttach == null)
                    {
                        return("");
                    }
                    if (mAttach.IsFromHTML())
                    {
                        for (int i = 0; i < mAttach._lines.Count; i++)
                        {
                            filePath = System.IO.Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "TempDownload");
                            filePath = System.IO.Path.Combine(filePath, mAttach.GetFile(mAttach._lines[i].Line_ID));
                            if (filePath.IndexOf("ERROR") > -1)
                            {
                                continue;
                            }
                            filePath = System.IO.Path.Combine(filePath, mAttach._lines[i].FileName);
                            sendmail.AddAttachment(new FileInfo(filePath));
                        }
                    }
                    else
                    {
                        foreach (MAttachmentEntry entry in mAttach.GetEntries())
                        {
                            sendmail.AddAttachment(entry.GetData(), entry.GetName());
                        }
                    }
                }

                Check = sendmail.Send();
                if (Check == "OK")
                {
                    count++;
                }
            }

            if (ds1 != null && ds1.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    if (Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "B" ||
                        Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "C" ||
                        Util.GetValueOfString(ds1.Tables[0].Rows[i]["NOTIFICATIONTYPE"]) == "N")
                    {
                        SendNotice(Message, Util.GetValueOfInt(ds1.Tables[0].Rows[i]["AD_USER_ID"]), AD_Org_ID, Ad_Client_ID);
                    }
                }
            }

            if (count > 0)
            {
                log.Fine("Email Sent Successfully");
                res = Msg.GetMsg(GetCtx(), "VIS_EmailSent");

                string sql = "UPDATE OFFICEMEMO SET PUBLISHDATE = " + GlobalVariable.TO_DATE(System.DateTime.Now, false) + ", PUBLISHTIME = " + GlobalVariable.TO_DATE(System.DateTime.Now, false) + ", PROCESSED = 'Y' WHERE OFFICEMEMO_ID = " + _OfficeMemoID;
                DB.ExecuteQuery(sql, null, null);
            }
            else
            {
                log.SaveError("Email Not Sent", "");
                res = Msg.GetMsg(GetCtx(), "VIS_EmailNotSent");
            }

            return(res);
        }