Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用SmtpClient发送邮件时图像中断_C#_Html_Email_Smtpclient - Fatal编程技术网

C# 使用SmtpClient发送邮件时图像中断

C# 使用SmtpClient发送邮件时图像中断,c#,html,email,smtpclient,C#,Html,Email,Smtpclient,我正在使用SmtpClient类使用C#发送邮件。在发送邮件之前,我正在做以下事情 var mailMessage = new MailMessage(); model.ToAddresses.ForEach(to => mailMessage.To.Add(to)); mailMessage.Subject = "Test Email - By Yasser"; mailMessage.Body = String.Format("{0}{1}{2}",

我正在使用
SmtpClient
类使用C#发送邮件。在发送邮件之前,我正在做以下事情

var mailMessage = new MailMessage();

model.ToAddresses.ForEach(to => mailMessage.To.Add(to));
mailMessage.Subject = "Test Email - By Yasser";

mailMessage.Body = String.Format("{0}{1}{2}",
                                    "<html><body>",
                                     GetEmailContent(model),
                                     "</body></html>");
mailMessage.IsBodyHtml = true;
return MailService.SendEmail(mailMessage);
现在,当我发送邮件时,邮件会被发送,以下是我在outlook中按view source时收到的邮件内容。下面是查看来源的电子邮件内容(显然我只保留了部分图像数据)


试验
你好,世界
缺少关闭h3标记

因此,这在邮件中看起来是不完整的(图像),但当我复制此源代码并将其粘贴到编辑器中,并使用浏览器打开文件时,一切看起来都很好(即使是图像)

更新:添加了outlook邮件的图像


有什么想法吗???

这是我尝试过的,并在outlook、thunderbird和gmail中测试过。很好

您可能需要查看我提到的以下资源以实现这一点:

示例代码:

// we need to use the prefix 'cid' in the img src value
string emailReadyHtml = string.empty;
emailReadyHtml += "<p>Hello World, below are two embedded images : </p>";
emailReadyHtml += "<img src=\"cid:yasser\" >";
emailReadyHtml += "<img src=\"cid:smile\" >";

MailMessage mailMessage = new MailMessage();

mailMessage.To.Add("yasser@mail.yy");
mailMessage.From = new MailAddress("info@mail.yy", "Info");

mailMessage.Subject = "Test Mail";
mailMessage.IsBodyHtml = true;

string image1Path = HttpContext.Current.Server.MapPath("~/Content/images/yasser.jpg");
byte[] image2Bytes = someArrayOfByte;

ContentType c = new ContentType("image/jpeg");

// create image resource from image path using LinkedResource class.
LinkedResource linkedResource1 = new LinkedResource(imagePath);
linkedResource1.ContentType = c ;
linkedResource1.ContentId = "yasser";
linkedResource1.TransferEncoding = TransferEncoding.Base64;

// the linked resource can be created from bytes also, which may be stored in database (which was my case)
LinkedResource linkedResource2 = new LinkedResource(new MemoryStream(image2Bytes));
linkedResource2.ContentType = c;
linkedResource2.ContentId = "smile";
linkedResource2.TransferEncoding = TransferEncoding.Base64;

AlternateView alternativeView = AlternateView.CreateAlternateViewFromString(emailReadyHtml, null, MediaTypeNames.Text.Html);

alternativeView.ContentId = "htmlView";
alternativeView.TransferEncoding = TransferEncoding.SevenBit;

alternativeView.LinkedResources.Add(linkedResource1) ;
alternativeView.LinkedResources.Add(linkedResource2);

mailMessage.AlternateViews.Add(alternativeView);

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
//我们需要在img src值中使用前缀'cid'
string emailReadyHtml=string.empty;
emailReadyHtml+=“你好,下面是两个嵌入的图像:

”; emailReadyHtml+=“”; emailReadyHtml+=“”; MailMessage MailMessage=新建MailMessage(); mailMessage.To.Add(“yasser@mail.yy"); mailMessage.From=新邮件地址(“info@mail.yy“,”信息“); mailMessage.Subject=“测试邮件”; mailMessage.IsBodyHtml=true; 字符串image1Path=HttpContext.Current.Server.MapPath(“~/Content/images/yasser.jpg”); byte[]image2Bytes=someArrayOfByte; ContentType c=新的ContentType(“图像/jpeg”); //使用LinkedResource类从映像路径创建映像资源。 LinkedResource linkedResource1=新的LinkedResource(imagePath); linkedResource1.ContentType=c; linkedResource1.ContentId=“yasser”; linkedResource1.Transferncode=Transferncode.Base64; //链接的资源也可以从字节创建,字节可以存储在数据库中(这是我的情况) LinkedResource linkedResource2=新的LinkedResource(新内存流(image2Bytes)); linkedResource2.ContentType=c; linkedResource2.ContentId=“微笑”; linkedResource2.Transferncode=Transferncode.Base64; AlternateView AlternateView=AlternateView.CreateAlternateView-FromString(emailReadyHtml,null,MediaTypeNames.Text.Html); alternativeView.ContentId=“htmlView”; alternativeView.Transferncode=Transferncode.SevenBit; alternativeView.LinkedResources.Add(linkedResource1); alternativeView.LinkedResources.Add(linkedResource2); mailMessage.alternativeviews.Add(alternativeView); SmtpClient SmtpClient=新的SmtpClient(); smtpClient.Send(mailMessage);
这里有一个函数可以解决这个问题。在发送电子邮件之前,请先呼叫它,如:

ProcessEmbeddingImages(mailMessage);
return MailService.SendEmail(mailMessage);
ProcessEmbeddingImages函数是在VB.Net中编写的,因此您可能希望使用其中一个在线转换器将其翻译为c

Private Sub ProcessEmbeddingImages(ByRef oMail As System.Net.Mail.MailMessage)
    Dim oLinkedResources As New Hashtable()
    oMail.Body = PadSrcDataImage(oMail.Body, oLinkedResources)
    If oLinkedResources.Count > 0 Then

        Dim oAlternateView As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(oMail.Body, Nothing, "text/html")
        oAlternateView.ContentId = "htmlView"
        oAlternateView.TransferEncoding = Net.Mime.TransferEncoding.SevenBit

        For Each oItem As DictionaryEntry In oLinkedResources
            Dim oKey As String() = Split(oItem.Key, "-")
            Dim i As Integer = oKey(0)
            Dim sExt As String = oKey(1)
            Dim sData As String = oItem.Value

            Dim oLinkedResource As New System.Net.Mail.LinkedResource(New IO.MemoryStream(System.Convert.FromBase64String(sData)))
            oLinkedResource.ContentId = "MyImg" & i
            oLinkedResource.TransferEncoding = Net.Mime.TransferEncoding.Base64
            oLinkedResource.ContentType = New System.Net.Mime.ContentType("image/" & sExt)
            oAlternateView.LinkedResources.Add(oLinkedResource)
        Next

        oMail.AlternateViews.Add(oAlternateView)
    End If
End Sub

Private Function PadSrcDataImage(ByVal sHtml As String, ByRef oLinkedResources As Hashtable) As String

    Dim oList As New ArrayList
    Dim sSearch As String = "\ssrc=['""]data:image/(.*?);base64,(.*?)['""]"

    Dim oMatches As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(sHtml, sSearch, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
    For Each m As System.Text.RegularExpressions.Match In oMatches
        If m.Groups.Count >= 2 Then
            Dim sExt As String = m.Groups(1).Value
            Dim sData As String = m.Groups(2).Value

            If sData.Length > 7 AndAlso Right(sData, 6) = "%3D%3D" Then
                'Replace trailing %3D%3D with ==
                sData = Left(sData, sData.Length - 6) & "=="
            End If

            oLinkedResources.Add(oLinkedResources.Count & "-" & sExt, sData)

            Dim iPos1 As Integer = m.Groups(1).Index - "data:image/".Length
            Dim iPos2 As Integer = m.Groups(2).Index + m.Groups(2).Length
            Dim iPoints As Integer() = {iPos1, iPos2}
            oList.Add(iPoints)
        End If
    Next

    Dim sRet As String = ""

    If oList.Count = 1 Then 'One img
        Dim iPoints As Integer() = oList(0)
        Dim sStr1 As String = sHtml.Substring(0, iPoints(0))
        Dim sStr2 As String = sHtml.Substring(iPoints(1))
        sRet = sStr1 & "cid:MyImg0" & sStr2

    ElseIf oList.Count > 1 Then

        For i As Integer = 0 To oList.Count - 1
            Dim iPoints As Integer() = oList(i)
            Dim iPos1 As Integer = iPoints(0)

            If i = 0 Then
                'First img
                Dim sStr1 As String = sHtml.Substring(0, iPos1)
                sRet += sStr1 & "cid:MyImg" & i

            Else 'Rest imgs
                Dim iPrevPos2 As Integer = oList(i - 1)(1)
                Dim sStr1 As String = sHtml.Substring(iPrevPos2, iPos1 - iPrevPos2)
                sRet += sStr1 & "cid:MyImg" & i

                If i = oList.Count - 1 Then    'Last
                    sRet += sHtml.Substring(iPoints(1))
                End If
            End If
        Next
    End If

    If sRet <> "" Then
        Return sRet
    Else
        Return sHtml
    End If
End Function
私有子进程EmbeddingImages(ByRef oMail作为System.Net.Mail.MailMessage)
Dim OlinkdResources作为新哈希表()
oMail.Body=PadSrcDataImage(oMail.Body,oLinkedResources)
如果OlinkdResources.Count>0,则
Dim oAlternateView作为System.Net.Mail.AlternateView=System.Net.Mail.AlternateView.CreateAlternateViewFromString(oMail.Body,Nothing,“text/html”)
oAlternateView.ContentId=“htmlView”
OAAlternateView.Transferncode=Net.Mime.Transferncode.SevenBit
对于作为字典的每个oItem,在oLinkedResources中输入
Dim oKey As String()=拆分(oItem.Key,“-”)
Dim i作为整数=oKey(0)
Dim sExt As String=OK(1)
作为字符串的Dim sData=oItem.Value
将OlinkdResource设置为新的System.Net.Mail.LinkedResource(新的IO.MemoryStream(System.Convert.FromBase64String(sData)))
oLinkedResource.ContentId=“MyImg”&i
oLinkedResource.Transferncode=Net.Mime.Transferncode.Base64
oLinkedResource.ContentType=New System.Net.Mime.ContentType(“image/”&sExt)
OAAlternateView.LinkedResources.Add(oLinkedResource)
下一个
oMail.AlternateViews.Add(oAlternateView)
如果结束
端接头
私有函数padscrcdataimage(ByVal sHtml作为字符串,ByRef oLinkedResources作为哈希表)作为字符串
作为新ArrayList的Dim oList
Dim sSearch As String=“\ssrc=[”]数据:image/(.*);base64,(.*)['']
Dim OMATCH为System.Text.RegularExpressions.MatchCollection=System.Text.RegularExpressions.Regex.Matches(sHtml、sSearch、System.Text.RegularExpressions.RegexOptions.IgnoreCase)
对于OMATCH中的每个m As System.Text.RegularExpressions.Match
如果m.Groups.Count>=2,则
Dim sExt作为字符串=m.Groups(1).Value
作为字符串的Dim sData=m.Groups(2).Value
如果sData.Length>7且同样正确(sData,6)=%3D%3D”,则
'将尾部的%3D%3D替换为==
sData=左(sData,sData.Length-6)和“=”
如果结束
添加(oLinkedResources.Count&“-”&sExt,sData)
Dim iPos1为整数=m.Groups(1).索引-“数据:image/”.长度
Dim iPos2为整数=m.Groups(2).索引+m.Groups(2).长度
Dim iPoints As Integer()={iPos1,iPos2}
oList.Add(iPoints)
如果结束
下一个
Dim sRet As String=“”
如果oList.Count=1,则“一个img
Dim iPoints作为整数()=oList(0)
Dim sStr1作为字符串=sHtml.子字符串(0,iPoints(0))
Dim sStr2作为字符串=sHtml.子字符串(iPoints(1))
sRet=sStr1和“cid:MyImg0”和sStr2
ElseIf oList.然后计数>1
对于i,整数=0到oList.Count-1
Dim IPOINT作为整数()=oList(i)
Dim iPos1为整数=iPoints(0)
如果i=0,那么
“第一个img
Dim sStr1作为字符串=sHtml.子字符串(0,iPos1)
sRet+=sStr1和“cid:MyImg”和i
其他人的休息时间
模糊知识产权
ProcessEmbeddingImages(mailMessage);
return MailService.SendEmail(mailMessage);
Private Sub ProcessEmbeddingImages(ByRef oMail As System.Net.Mail.MailMessage)
    Dim oLinkedResources As New Hashtable()
    oMail.Body = PadSrcDataImage(oMail.Body, oLinkedResources)
    If oLinkedResources.Count > 0 Then

        Dim oAlternateView As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(oMail.Body, Nothing, "text/html")
        oAlternateView.ContentId = "htmlView"
        oAlternateView.TransferEncoding = Net.Mime.TransferEncoding.SevenBit

        For Each oItem As DictionaryEntry In oLinkedResources
            Dim oKey As String() = Split(oItem.Key, "-")
            Dim i As Integer = oKey(0)
            Dim sExt As String = oKey(1)
            Dim sData As String = oItem.Value

            Dim oLinkedResource As New System.Net.Mail.LinkedResource(New IO.MemoryStream(System.Convert.FromBase64String(sData)))
            oLinkedResource.ContentId = "MyImg" & i
            oLinkedResource.TransferEncoding = Net.Mime.TransferEncoding.Base64
            oLinkedResource.ContentType = New System.Net.Mime.ContentType("image/" & sExt)
            oAlternateView.LinkedResources.Add(oLinkedResource)
        Next

        oMail.AlternateViews.Add(oAlternateView)
    End If
End Sub

Private Function PadSrcDataImage(ByVal sHtml As String, ByRef oLinkedResources As Hashtable) As String

    Dim oList As New ArrayList
    Dim sSearch As String = "\ssrc=['""]data:image/(.*?);base64,(.*?)['""]"

    Dim oMatches As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(sHtml, sSearch, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
    For Each m As System.Text.RegularExpressions.Match In oMatches
        If m.Groups.Count >= 2 Then
            Dim sExt As String = m.Groups(1).Value
            Dim sData As String = m.Groups(2).Value

            If sData.Length > 7 AndAlso Right(sData, 6) = "%3D%3D" Then
                'Replace trailing %3D%3D with ==
                sData = Left(sData, sData.Length - 6) & "=="
            End If

            oLinkedResources.Add(oLinkedResources.Count & "-" & sExt, sData)

            Dim iPos1 As Integer = m.Groups(1).Index - "data:image/".Length
            Dim iPos2 As Integer = m.Groups(2).Index + m.Groups(2).Length
            Dim iPoints As Integer() = {iPos1, iPos2}
            oList.Add(iPoints)
        End If
    Next

    Dim sRet As String = ""

    If oList.Count = 1 Then 'One img
        Dim iPoints As Integer() = oList(0)
        Dim sStr1 As String = sHtml.Substring(0, iPoints(0))
        Dim sStr2 As String = sHtml.Substring(iPoints(1))
        sRet = sStr1 & "cid:MyImg0" & sStr2

    ElseIf oList.Count > 1 Then

        For i As Integer = 0 To oList.Count - 1
            Dim iPoints As Integer() = oList(i)
            Dim iPos1 As Integer = iPoints(0)

            If i = 0 Then
                'First img
                Dim sStr1 As String = sHtml.Substring(0, iPos1)
                sRet += sStr1 & "cid:MyImg" & i

            Else 'Rest imgs
                Dim iPrevPos2 As Integer = oList(i - 1)(1)
                Dim sStr1 As String = sHtml.Substring(iPrevPos2, iPos1 - iPrevPos2)
                sRet += sStr1 & "cid:MyImg" & i

                If i = oList.Count - 1 Then    'Last
                    sRet += sHtml.Substring(iPoints(1))
                End If
            End If
        Next
    End If

    If sRet <> "" Then
        Return sRet
    Else
        Return sHtml
    End If
End Function