Отправка растрового изображения по почтовому протоколу SMTP с использованием c #, отображение поврежденных изображений - PullRequest
0 голосов
/ 07 ноября 2018

Я пытаюсь отправить свое растровое изображение в почтовом вложении с помощью sendgrid через веб-приложение. Но это немного сложно.

Сначала я генерирую пароль через класс генератора паролей, как показано ниже.

 public class PasswordGenerator
    {
        public PasswordGenerator()
        {
            this.Minimum = DefaultMinimum;
            this.Maximum = DefaultMaximum;
            this.ConsecutiveCharacters = false;
            this.RepeatCharacters = true;
            this.ExcludeSymbols = false;
            this.Exclusions = null;

            rng = new RNGCryptoServiceProvider();
        }

        protected int GetCryptographicRandomNumber(int lBound, int uBound)
        {
            // Assumes lBound >= 0 && lBound < uBound
            // returns an int >= lBound and < uBound
            uint urndnum;
            byte[] rndnum = new Byte[4];
            if (lBound == uBound - 1)
            {
                // test for degenerate case where only lBound can be returned
                return lBound;
            }

            uint xcludeRndBase = (uint.MaxValue -
                (uint.MaxValue % (uint)(uBound - lBound)));

            do
            {
                rng.GetBytes(rndnum);
                urndnum = System.BitConverter.ToUInt32(rndnum, 0);
            } while (urndnum >= xcludeRndBase);

            return (int)(urndnum % (uBound - lBound)) + lBound;
        }

        protected char GetRandomCharacter()
        {
            int upperBound = pwdCharArray.GetUpperBound(0);

            if (true == this.ExcludeSymbols)
            {
                upperBound = UBoundDigit;
            }

            int randomCharPosition = GetCryptographicRandomNumber(
                pwdCharArray.GetLowerBound(0), upperBound);

            char randomChar = pwdCharArray[randomCharPosition];

            return randomChar;
        }

        public string Generate()
        {
            // Pick random length between minimum and maximum   
            int pwdLength = GetCryptographicRandomNumber(Minimum,
                Maximum);

            System.Text.StringBuilder pwdBuffer = new System.Text.StringBuilder
            {
                Capacity = this.Maximum
            };

            // Generate random characters
            char lastCharacter, nextCharacter;

            // Initial dummy character flag
            lastCharacter = nextCharacter = '\n';

            for (int i = 0; i < pwdLength; i++)
            {
                nextCharacter = GetRandomCharacter();

                if (false == this.ConsecutiveCharacters)
                {
                    while (lastCharacter == nextCharacter)
                    {
                        nextCharacter = GetRandomCharacter();
                    }
                }

                if (false == this.RepeatCharacters)
                {
                    string temp = pwdBuffer.ToString();
                    int duplicateIndex = temp.IndexOf(nextCharacter);
                    while (-1 != duplicateIndex)
                    {
                        nextCharacter = GetRandomCharacter();
                        duplicateIndex = temp.IndexOf(nextCharacter);
                    }
                }

                if ((null != this.Exclusions))
                {
                    while (-1 != this.Exclusions.IndexOf(nextCharacter))
                    {
                        nextCharacter = GetRandomCharacter();
                    }
                }

                pwdBuffer.Append(nextCharacter);
                lastCharacter = nextCharacter;
            }

            if (null != pwdBuffer)
            {
                return pwdBuffer.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        public string Exclusions { get; set; }

        public int Minimum
        {
            get { return this.minSize; }
            set
            {
                this.minSize = value;
                if (PasswordGenerator.DefaultMinimum > this.minSize)
                {
                    this.minSize = PasswordGenerator.DefaultMinimum;
                }
            }
        }

        public int Maximum
        {
            get { return this.maxSize; }
            set
            {
                this.maxSize = value;
                if (this.minSize >= this.maxSize)
                {
                    this.maxSize = PasswordGenerator.DefaultMaximum;
                }
            }
        }

        public bool ExcludeSymbols { get; set; }

        public bool RepeatCharacters { get; set; }

        public bool ConsecutiveCharacters { get; set; }

        private const int DefaultMinimum = 15;
        private const int DefaultMaximum = 17;
        private const int UBoundDigit = 61;

        private RNGCryptoServiceProvider rng;
        private int minSize;
        private int maxSize;
        private char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<.>/?".ToCharArray();
    }

При событии загрузки страницы я создаю его объект и передаю его значение в сеанс, а затем в строку, затем эту строку в мое тело письма, этот пароль также передается в мой растровый класс, как показано ниже.

private Bitmap CreateBitmapImage(string sImageText)
    {
        Bitmap objBmpImage = new Bitmap(1, 1);

        int intWidth = 0;
        int intHeight = 0;

        // Create the Font object for the image text drawing.
        Font objFont = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);

        // Create a graphics object to measure the text's width and height.
        Graphics objGraphics = Graphics.FromImage(objBmpImage);

        // This is where the bitmap size is determined.
        intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
        intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;

        // Create the bmpImage again with the correct size for the text and font.
        objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

        // Add the colors to the new bitmap.
        objGraphics = Graphics.FromImage(objBmpImage);

        // Set Background color
        objGraphics.Clear(Color.White);
        objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
        objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
        objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
        objGraphics.Flush();
        return (objBmpImage);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["displayname"] == null)
        {
            Response.Redirect("OTP.aspx");
        }

        MessageLabel.Text = "User:" + Session["displayname"].ToString();
        PasswordGenerator pass = new PasswordGenerator();
        Session["sspr_password"] = pass.Generate();

}

Моя почта вроде как функция

MailMessage mailMsg = new MailMessage();
                mailMsg.To.Add(new MailAddress(Session["emailid"].ToString(), Session["displayname"].ToString()));
                mailMsg.From = new MailAddress("no_reply@sspr.com", "SSPR");
                mailMsg.Subject = "SSPR | Password";

                string html = @"Greetings " + Session["displayname"].ToString() + "!!! <br>" + "<br>" + "Your new password is " + Session["sspr_password"].ToString();
                string password = Session["sspr_password"].ToString();
                Bitmap bitpass = CreateBitmapImage(password);
                var stream = new MemoryStream();
                stream.Position = 0;
                bitpass.Save(stream, ImageFormat.Png);
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(
                      html, null, MediaTypeNames.Text.Html));

                mailMsg.Attachments.Add(new Attachment(stream, "password.png")); 
               SmtpClient client = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(
                  "azure@azure.com", "....u");
                client.Credentials = credentials;
                client.Send(mailMsg);
                      }

Все работает, я получаю почту, а также я получаю вложение, но когда я открываю свой пароль png. Показывает «Не удалось загрузить изображение» here Может кто-нибудь сказать мне, почему?

Спасибо

...