Announcement

Collapse
No announcement yet.

gửi mail có hình ảnh không phải là đính kèm trong Wpf

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • [C#] gửi mail có hình ảnh không phải là đính kèm trong Wpf

    Mấy anh cho em hỏi, khi mình soạn thảo mail thì có thể chèn 1 cái Image vào nhưng khi gửi thì bên nhận không nhận được. ai biết chỉ em với
    đây là đoạn code
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using DevExpress.Xpf.Core;
    using DevExpress.Xpf.Ribbon;
    using DevExpress.Xpf.Bars;
    using DevExpress.XtraRichEdit;
    using System.Net.Mail;
    using System.Net;
    using System.Drawing;
    using System.Net.NetworkInformation;
    using System.IO;
    using DevExpress.Xpf.Editors.Settings;
    using System.Windows.Threading;
    using Microsoft.Win32;
    using System.Windows.Controls.Primitives;
    using DevExpress.XtraRichEdit.Commands;
    using MarkupConverter;
    
    namespace DXWPFApplication1
    {
        public partial class MainWindow : DXRibbonWindow
        {
            IMarkupConverter markupconverter = new MarkupConverter.MarkupConverter();
            public MainWindow()
            {
                InitializeComponent();
                #region
                ((ComboBoxEditSettings)eFontSize.EditSettings).ItemsSource = (new FontSizes()).Items;
                Body.FontSize = 14;
                toAddress.FontSize = 14;
                Subject.FontSize = 14;
                #endregion
            }
    
            void ApplyPropertyValueToSelectedText(DependencyProperty formattingProperty, object value)
            {
                if (value == null) return;
                Body.Selection.ApplyPropertyValue(formattingProperty, value);
            }
            #region font
            private void bcorlor_EditValueChanged(object sender, RoutedEventArgs e)
            {
                System.Windows.Media.BrushConverter a = new BrushConverter();
    
                Body.Selection.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                    a.ConvertFromString(bcorlor.EditValue.ToString()));
            }
    
            void eEditFont_EditValueChanged(object sender, RoutedEventArgs e)
            {
    
                try
                {
                    ApplyPropertyValueToSelectedText(TextElement.FontFamilyProperty, eEditFont.EditValue);
                }
                catch
                {
                    return;
                }
            }
    
            private void eFontSize_EditValueChanged(object sender, RoutedEventArgs e)
            {
                try
                {
                    ApplyPropertyValueToSelectedText(TextElement.FontSizeProperty, eFontSize.EditValue);
                }
                catch
                {
                    return;
                }
            }
            #endregion
            #region app.menu
            void bSend_ItemClick(object sender, ItemClickEventArgs e)
            {
                
                
                string username = "username";
                MailAddress user = new MailAddress(username);
                string pass = "password";
                if (toAddress.Text == "")
                    MessageBox.Show("To Address Not Find", "Error",MessageBoxButton.OK);
                else
                {
                    MailMessage message = new MailMessage();
                    message.From = user;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    message.IsBodyHtml = true;
                    message.Body = (new TextRange(Body.Document.ContentStart, Body.Document.ContentEnd)).Text;
                    //message.Body = markupconverter.ConvertRtfToHtml(new TextRange(Body.Document.ContentStart, Body.Document.ContentEnd).Text);
                    string[] mailTo = this.toAddress.Text.Trim().Split(';');
                    foreach (var item in mailTo)
                    {
                        message.To.Add(item);
                    }
                    message.Subject = Subject.Text;
                    client.EnableSsl = true;
                    if (NetworkInterface.GetIsNetworkAvailable() == false)
                    {
                        MessageBox.Show("NetWork Not Available", "Mail Sent");
                        return;
                    }
                    if (lbattach.Content != null)
                    {
                        string[] cFileName;
                        cFileName = lbattach.Content.ToString().Trim().Split(';');
                        for (int i = 0; i < cFileName.Length -1; i++)
                        {
                            Attachment nAttacch = new Attachment(cFileName[i]);
                            message.Attachments.Add(nAttacch);
                        }
                    }
                    try
                    {
                        client.Credentials = new NetworkCredential(username, pass);
                        
                        
    
                        client.Send(message);
                        MessageBox.Show("Mail Sent", "Sender");
                    }
                    catch
                    {
                        MessageBox.Show("Login Fail", "Send Message",MessageBoxButton.OKCancel);
                    }
                }
            }
    
            void bClose_ItemClick(object sender, ItemClickEventArgs e)
            {
                this.Close();
                
            }
            #endregion
            #region fontstyle
            private void chBoil_CheckedChanged(object sender, ItemClickEventArgs e)
            {
                if (chBoil.IsChecked == true)
                    Body.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold);
                else
                    Body.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal);
            }
    
            private void chItalic_CheckedChanged(object sender, ItemClickEventArgs e) 
            {
                if (chItalic.IsChecked == true)
                    Body.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Italic);
                else
                    Body.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Normal);
            }
    
            private void chUnderline_CheckedChanged_1(object sender, ItemClickEventArgs e)
            {
                if (chUnderline.IsChecked == true)
                    Body.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline);
                else
                    Body.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, null);
            }
            #endregion
            #region insert
            private void bAttach_ItemClick(object sender, ItemClickEventArgs e)
            {
                OpenFileDialog attFile = new OpenFileDialog();
                attFile.Filter = "All File|*.*";
                attFile.Multiselect = true;
                attFile.ShowDialog();
                if (!string.IsNullOrEmpty(attFile.FileName))
                {
                    this.lbattach.Visibility = Visibility.Visible;
                    FileInfo fe = new FileInfo(attFile.FileName);
                    if (fe.Extension == "exe")
                    {
                        MessageBox.Show("Can't attachment file Application", "Attachment", MessageBoxButton.OKCancel);
                        return;
                    }
                    else
                    {
                        foreach (var item in attFile.FileNames)
                        {
                            lbattach.Content = lbattach.Content + item + ";";
                        }                   
                    }
                }
            }
    
            private void addLink_ItemClick_1(object sender, ItemClickEventArgs e)
            {
                Hyperlink myLink = new Hyperlink();
                myLink.Inlines.Add(Body.Selection.Text);
                try
                {
                    myLink.NavigateUri = new Uri(nameLink.EditValue.ToString());
                }
                catch
                {
                    MessageBox.Show("Error: Link not available", "Hyperlink", MessageBoxButton.OK);
                }
    
                Paragraph pa = new Paragraph();
                pa.Inlines.Add(myLink);
                Body.Selection.Text = "";
                Body.Document.Blocks.Add(pa);
            }
    
            private void bPicture_ItemClick_1(object sender, ItemClickEventArgs e)
            {
                OpenFileDialog opdl = new OpenFileDialog();
                opdl.ShowDialog();
                opdl.CheckFileExists = true;
                opdl.CheckPathExists = true;
                string path = opdl.FileName;
                if (path != "")
                {
                    Image myImage = new Image();
                    myImage.Source = new BitmapImage(new Uri(path));
                    myImage.Height = 300;
                    myImage.Width = 400;
                    InlineUIContainer MyUI = new InlineUIContainer();
                    MyUI.Child = myImage;
                    Paragraph pa = new Paragraph();
                    pa.Inlines.Add(MyUI);
                    Body.Document.Blocks.Add(pa);
                }
                else
                    return;
            }
    
            #endregion      
            public void html() 
            {
                
            }
        }
        public class FontSizes
        {
            public double[] Items
            {
                get
                {
                    return new double[] { 
                3.0, 4.0, 5.0, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 
                10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 15.0,
                16.0, 17.0, 18.0, 19.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0,
                32.0, 34.0, 36.0, 38.0, 40.0, 44.0, 48.0, 52.0, 56.0, 60.0, 64.0, 68.0, 72.0, 76.0,
                80.0, 88.0, 96.0, 104.0, 112.0, 120.0, 128.0, 136.0, 144.0
                };
                }
            }
        }
    }
    còn đây là đoạn code giao diện
    Code:
    <dxr:DXRibbonWindow
        xmlns:local="clr-namespace:DXWPFApplication1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        
        xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxr="http://schemas.devexpress.com/winfx/2008/xaml/ribbon"
        xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars"
        xmlns:dxbh="http://schemas.devexpress.com/winfx/2008/xaml/bars/internal"
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
        xmlns:dxd="http://schemas.devexpress.com/winfx/2008/xaml/docking"
        xmlns:dxre="http://schemas.devexpress.com/winfx/2008/xaml/richedit"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
        x:Class="DXWPFApplication1.MainWindow"
        Title="New Message" Height="400" Width="800"
        Background="AliceBlue"
        SnapsToDevicePixels="True" UseLayoutRounding="True"
        >
        <dxr:DXRibbonWindow.Resources>
    
            <ResourceDictionary>
            </ResourceDictionary>
    
        </dxr:DXRibbonWindow.Resources>
        <dxb:BarManager x:Name="barManager" dxbh:BlendHelperForBarsAndRibbon.IsDesignControl="True" Focusable="True" 
                        AddNewItems="True" >
    
            <dxb:BarManager.Items>
                <dxb:BarEditItem x:Name="eEditFont" EditWidth="150" EditValue="Times New Roman" EditValueChanged="eEditFont_EditValueChanged">
                    <dxb:BarEditItem.EditSettings>
                        <dxe:FontEditSettings />
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxb:BarEditItem  Name="eFontSize" EditWidth="50" EditValue="12" EditValueChanged="eFontSize_EditValueChanged" >
                    <dxb:BarEditItem.EditSettings>
                        <dxe:ComboBoxEditSettings/>
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxb:BarCheckItem x:Name="chBoil" Glyph="Images/Icons/bold-16x16.png" AllowUncheckInGroup="True" KeyGesture="Ctrl+B" CheckedChanged="chBoil_CheckedChanged" >
                </dxb:BarCheckItem>
                <dxb:BarCheckItem x:Name="chItalic" Glyph="Images/Icons/italic-16x16.png" KeyGesture="Ctrl+I" CheckedChanged="chItalic_CheckedChanged"/>
                <dxb:BarCheckItem x:Name="chUnderline" Glyph="Images/Icons/underline-16x16.png" KeyGesture="Ctrl+U" CheckedChanged="chUnderline_CheckedChanged_1"/>
                <dxb:BarButtonItem x:Name="bHelp" Content="Help" Glyph="Images/Icons/Online_Help.png" LargeGlyph="Images/Icons/Online_Help.png" KeyGesture="F1"/>
                <dxb:BarButtonItem x:Name="bClose" Content="Close" Glyph="Images/Icons/close-32x32.png" LargeGlyph="Images/Icons/close-32x32.png" KeyGesture="Ctrl+Esc" ItemClick="bClose_ItemClick"/>
                <dxb:BarButtonItem x:Name="bCut"  Command="ApplicationCommands.Cut" Content="Cut" Glyph="Images/Icons/cut-32x32.png" LargeGlyph="Images/Icons/cut-32x32.png"/>
                <dxb:BarButtonItem x:Name="bCopy" Content="Copy" Command="ApplicationCommands.Copy" Glyph="Images/Icons/copy-32x32.png" LargeGlyph="Images/Icons/copy-32x32.png"/>
                <dxb:BarButtonItem x:Name="bPaste"  KeyGesture="Ctrl+v" Content="Paste" Command="ApplicationCommands.Paste" Glyph="Images/Icons/paste-32x32.png" LargeGlyph="Images/Icons/paste-32x32.png"/>
                <dxb:BarButtonItem x:Name="bSave" Content="Save" Glyph="Images/Icons/save-as-32x32.png" LargeGlyph="Images/Icons/save-as-32x32.png" KeyGesture="Ctrl+S"/>
                <dxb:BarButtonItem x:Name="bSend" Content="Send Message" Glyph="Images/Icons/Send.png" LargeGlyph="Images/Icons/Send.png" KeyGesture="Ctrl+Enter" ItemClick="bSend_ItemClick"/>
                <dxb:BarButtonItem x:Name="textLeft" Command="EditingCommands.AlignLeft" Glyph="Images/Icons/left-align-16x16.png" KeyGesture="Ctrl+Shift+L" />
                <dxb:BarButtonItem x:Name="textCenter" Command="EditingCommands.AlignCenter" Glyph="Images/Icons/center-align-16x16.png" KeyGesture="Ctrl+Shift+C" />
                <dxb:BarButtonItem x:Name="textRight" Command="EditingCommands.AlignRight" Glyph="Images/Icons/right-align-16x16.png" KeyGesture="Ctrl+Shift+R" />
                <dxb:BarButtonItem x:Name="bBulet" Command="EditingCommands.ToggleBullets" Glyph="Images/Icons/bullets-32x32.png" />
                <dxb:BarButtonItem x:Name="bNumberring" Command="EditingCommands.ToggleNumbering" Glyph="Images/Icons/ListNumbers_32x32.png" />
                <dxb:BarEditItem x:Name="bcorlor" EditValueChanged="bcorlor_EditValueChanged">
                    <dxb:BarEditItem.EditSettings>
                        <dxe:PopupColorEditSettings/>
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxb:BarEditItem x:Name="nameLink" EditHeight="30" EditWidth="100">
                    <dxb:BarEditItem.EditSettings>
                        <dxe:TextEditSettings/>
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxb:BarButtonItem x:Name="addLink" Content="AddLink" ItemClick="addLink_ItemClick_1"/>
                <dxb:BarButtonItem x:Name="bAttach" Content="Attachment" Glyph="Images/Icons/PaperClip4_Black.png" ItemClick="bAttach_ItemClick"/>
                <dxb:BarSubItem x:Name="bHyperlink"  Glyph="Images/Icons/hyperlink.PNG" Content="Hyperlink">
                    <dxb:BarEditItemLink BarItemName="nameLink"/>
                    <dxb:BarButtonItemLink BarItemName="addLink"/>
                </dxb:BarSubItem>
                <dxb:BarButtonItem x:Name="bPicture"  Glyph="Images/Icons/InsertPicture-32x32.png" Content="Picture" ItemClick="bPicture_ItemClick_1"/>
                <dxb:BarEditItem x:Name="row" EditWidth="50" EditHeight="30" Content="Row   ">
                    <dxb:BarEditItem.EditSettings>
                        <dxe:TextEditSettings/>
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxb:BarEditItem x:Name="colum" EditWidth="50" EditHeight="30" Content="Colum">
                    <dxb:BarEditItem.EditSettings>
                        <dxe:TextEditSettings  ValidateOnEnterKeyPressed="True"/>
                    </dxb:BarEditItem.EditSettings>
                </dxb:BarEditItem>
                <dxr:BarButtonGroup x:Name="Font" GlyphAlignment="Left">
                    <dxb:BarEditItemLink BarItemName="eEditFont" />
                    <dxb:BarEditItemLink BarItemName="eFontSize"/>
                </dxr:BarButtonGroup>
                <dxr:BarButtonGroup x:Name="Fontstyle" >
                    <dxb:BarCheckItemLink BarItemName="chBoil"/>
                    <dxb:BarCheckItemLink BarItemName="chItalic"/>
                    <dxb:BarCheckItemLink BarItemName="chUnderline"/>
                    <dxb:BarEditItemLink BarItemName="bcorlor"/>
                </dxr:BarButtonGroup>
                <dxr:BarButtonGroup x:Name="Align">
                    <dxb:BarButtonItemLink BarItemName="textLeft"/>
                    <dxb:BarButtonItemLink BarItemName="textCenter"/>
                    <dxb:BarButtonItemLink BarItemName="textRight"/>
                    <dxb:BarItemLink BarItemName="bBulet"/>
                    <dxb:BarItemLink BarItemName="bNumberring" RibbonStyle="Large"/>
                </dxr:BarButtonGroup>
            </dxb:BarManager.Items>
            <DockPanel IsManipulationEnabled="True">
                <dxr:RibbonControl x:Name="ribbonControl1" RibbonStyle="Office2010" dxbh:BlendHelperForBarsAndRibbon.IsDesignControl="true" DockPanel.Dock="Top">
                    <dxr:RibbonControl.ApplicationMenu>
                        <dxr:ApplicationMenu>
                            <dxb:BarButtonItemLink BarItemName="bSend" />
                            <dxb:BarButtonItemLink BarItemName="bSave" />
                            <dxb:BarButtonItemLink BarItemName="bHelp"  />
                            <dxb:BarButtonItemLink BarItemName="bClose" />
                        </dxr:ApplicationMenu>
                    </dxr:RibbonControl.ApplicationMenu>
                    <dxr:RibbonControl.PageHeaderItemLinks>
                        <dxb:BarButtonItemLink BarItemName="bHelp" />
                    </dxr:RibbonControl.PageHeaderItemLinks>
                    <dxr:RibbonControl.ToolbarItemLinks>
                        <dxb:BarButtonItemLink BarItemName="bCut" />
                        <dxb:BarButtonItemLink BarItemName="bCopy" />
                        <dxb:BarButtonItemLink BarItemName="bPaste" />
                    </dxr:RibbonControl.ToolbarItemLinks>
                    <dxr:RibbonDefaultPageCategory>
                        <dxr:RibbonPage x:Name="Home" Caption="Home">
                            <dxr:RibbonPageGroup Caption="Send">
                                <dxb:BarButtonItemLink BarItemName="bSend" />
                            </dxr:RibbonPageGroup>
                            <dxr:RibbonPageGroup Caption="ClipBoard">
                                <dxb:BarButtonItemLink BarItemName="bPaste" RibbonStyle="Large"/>
                                <dxb:BarButtonItemLink BarItemName="bCut" RibbonStyle="Large" />
                                <dxb:BarButtonItemLink BarItemName="bCopy" RibbonStyle="Large" />
                            </dxr:RibbonPageGroup>
                            <dxr:RibbonPageGroup Caption="Font">
                                <dxr:BarButtonGroupLink BarItemName="Font"/>
                                <dxr:BarButtonGroupLink BarItemName="Fontstyle"/>
                                <dxr:BarButtonGroupLink BarItemName="Align"/>
                            </dxr:RibbonPageGroup>
                            <dxr:RibbonPageGroup Caption="Insert">
                                <dxb:BarButtonItemLink BarItemName="bPicture" RibbonStyle="Large"/>
                                <dxb:BarItemLink BarItemName="bHyperlink" RibbonStyle="Large"/>
                                <dxb:BarButtonItemLink BarItemName="bAttach" RibbonStyle="Large"/>
                            </dxr:RibbonPageGroup>
                        </dxr:RibbonPage>
                    </dxr:RibbonDefaultPageCategory>
                </dxr:RibbonControl>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="80" />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="32" />
                        <RowDefinition Height="32"/>
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Label Content="To" FontFamily="Time New Roman" FontSize="20" 
                           TextOptions.TextHintingMode="Fixed" Height="32" VerticalAlignment="Top" />
                    <Label Content="Subject" FontFamily="Time New Roman" FontSize="20" 
                           TextOptions.TextHintingMode="Fixed" Grid.Row="1"  Height="32" VerticalAlignment="Top" />
                    <TextBox x:Name="toAddress" Grid.Column="1" Margin="5,5,10,0" 
                             AcceptsReturn="True" Height="22" VerticalAlignment="Top" FontFamily="Times New Roman"/>
                    <TextBox x:Name="Subject" Grid.Column="1" Margin="5,5,10,0" Grid.Row="1" 
                             AcceptsReturn="True"  Height="22" VerticalAlignment="Top" FontFamily="Times New Roman"/>
                    <RichTextBox x:Name="Body" Grid.Row="3" Grid.ColumnSpan="2" Margin="10,5.5,10,10" AcceptsReturn="True" 
                             AcceptsTab="True" ScrollViewer.CanContentScroll="True" FontFamily="Times New Roman" 
                             VerticalScrollBarVisibility="Auto" IsUndoEnabled="True" IsDocumentEnabled="True" FontSize="14">
                    </RichTextBox>
                    <Label Name="lbattach" Height="30" Grid.Column="1" Margin="5,2,10,0" Grid.Row="2" Visibility="Collapsed"/>
    
                </Grid>
                <dxe:ColorEdit Height="Auto" VerticalAlignment="Top" Width="Auto"/>
                <dxe:ColorEdit Height="Auto" VerticalAlignment="Top" Width="Auto"/>
            </DockPanel>
        </dxb:BarManager>
    </dxr:DXRibbonWindow>[ATTACH=CONFIG]8301[/ATTACH]

  • #2
    sao hok ai trả lời vậy ta???:sad:

    Comment


    • #3
      Theo như cậu nói thì mình hiểu là Image nằm trong RichTexBox chứ không nằm trong phần attach

      PHP Code:
      message.Body = (new TextRange(Body.Document.ContentStartBody.Document.ContentEnd)).Text
      Ở RichTextBox với x:Name = Body cậu chỉ lấy thuộc tính text của nó gửi đi nên làm sao có ảnh trong message.Body được.

      Một email muốn hiển thị hình ảnh mà không nằm trong mục attach thì nó cần có định dạng html (theo như mình biết là thế), nghĩa là hình ảnh mà cậu gửi phải được lưu trữ sẵn trên mạng (source), sau đó chỉ cần chèn thẻ image vô html với nguồn là source.

      Comment


      • #4
        mình đã thử chuyển body thành html rồi nhưng mà chỉ gửi được định dạng chứ còn image thì k gửi được

        Comment

        LHQC

        Collapse
        Working...
        X