使用C#通过SMTP邮件协议发送位图图像,显示损坏的图像

时间:2018-11-07 19:04:46

标签: c# email bitmap active-directory sendgrid

我正在尝试通过webapp使用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 谁能告诉我为什么?

谢谢

0 个答案:

没有答案