Announcement

Collapse
No announcement yet.

Datei an email anhängen

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

  • Datei an email anhängen

    Hallo zusammen!

    Ich möchte von meinem Programm aus, eine Support Email verschicken können. Das aufrufen des Email Clients ist kein Problem, wie kann ich jedoch eine Datei anhängen?

  • #2
    Was machst du bisher?

    Ich würde sowas über Simple MAPI erledigen.

    Comment


    • #3
      Hallo,

      du hast 2 Möglichkeiten die einfach sind (es gibt natürlich noch mehr, über COM, ...):
      1. wie Bernhard schon vorgeschlagen hat über (Simple) MAPI. Die Email wird so über den Standard-Mail-Client des Benutzers verschickt und wahlweise mit Benutzerinteraktion oder nicht
      2. ohne dass der Benutzer das Senden bestätigen muss gehts auch mit den .net-Boardmitteln


      Beispiel zu MAPI:
      Email.cs (Kapselung des MAPI):
      Code:
      using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Runtime.InteropServices;
      using System.Windows.Forms;
      
      namespace gfoidl.Tools.Email
      {
      	public class MAPI
      	{
      		public bool AddRecipientTo(string email)
      		{
      			return AddRecipient(email, HowTo.MAPI_TO);
      		}
      
      		public bool AddRecipientCC(string email)
      		{
      			return AddRecipient(email, HowTo.MAPI_TO);
      		}
      
      		public bool AddRecipientBCC(string email)
      		{
      			return AddRecipient(email, HowTo.MAPI_TO);
      		}
      
      		public void AddAttachment(string strAttachmentFileName)
      		{
      			m_attachments.Add(strAttachmentFileName);
      		}
      
      		public int SendMailPopup(string strSubject, string strBody)
      		{
      			return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
      		}
      
      		public int SendMailDirect(string strSubject, string strBody)
      		{
      			return SendMail(strSubject, strBody, MAPI_LOGON_UI);
      		}
      
      
      		[DllImport("MAPI32.DLL")]
      		static extern int MAPISendMail(IntPtr sess, IntPtr hwnd,
      			MapiMessage message, int flg, int rsv);
      
      		int SendMail(string strSubject, string strBody, int how)
      		{
      			MapiMessage msg = new MapiMessage();
      			msg.subject = strSubject;
      			msg.noteText = strBody;
      
      			msg.recips = GetRecipients(out msg.recipCount);
      			msg.files = GetAttachments(out msg.fileCount);
      
      			m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how,
      				0);
      			if (m_lastError > 1)
      				MessageBox.Show("MAPISendMail failed! " + GetLastError(),
      					"MAPISendMail");
      
      			Cleanup(ref msg);
      			return m_lastError;
      		}
      
      		bool AddRecipient(string email, HowTo howTo)
      		{
      			MapiRecipDesc recipient = new MapiRecipDesc();
      
      			recipient.recipClass = (int)howTo;
      			recipient.name = email;
      			m_recipients.Add(recipient);
      
      			return true;
      		}
      
      		IntPtr GetRecipients(out int recipCount)
      		{
      			recipCount = 0;
      			if (m_recipients.Count == 0)
      				return IntPtr.Zero;
      
      			int size = Marshal.SizeOf(typeof(MapiRecipDesc));
      			IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
      
      			int ptr = (int)intPtr;
      			foreach (MapiRecipDesc mapiDesc in m_recipients)
      			{
      				Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
      				ptr += size;
      			}
      
      			recipCount = m_recipients.Count;
      			return intPtr;
      		}
      
      		IntPtr GetAttachments(out int fileCount)
      		{
      			fileCount = 0;
      			if (m_attachments == null)
      				return IntPtr.Zero;
      
      			if ((m_attachments.Count <= 0) || (m_attachments.Count >
      				maxAttachments))
      				return IntPtr.Zero;
      
      			int size = Marshal.SizeOf(typeof(MapiFileDesc));
      			IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);
      
      			MapiFileDesc mapiFileDesc = new MapiFileDesc();
      			mapiFileDesc.position = -1;
      			int ptr = (int)intPtr;
      
      			foreach (string strAttachment in m_attachments)
      			{
      				mapiFileDesc.name = Path.GetFileName(strAttachment);
      				mapiFileDesc.path = strAttachment;
      				Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
      				ptr += size;
      			}
      
      			fileCount = m_attachments.Count;
      			return intPtr;
      		}
      
      		void Cleanup(ref MapiMessage msg)
      		{
      			int size = Marshal.SizeOf(typeof(MapiRecipDesc));
      			int ptr = 0;
      
      			if (msg.recips != IntPtr.Zero)
      			{
      				ptr = (int)msg.recips;
      				for (int i = 0; i < msg.recipCount; i++)
      				{
      					Marshal.DestroyStructure((IntPtr)ptr,
      						typeof(MapiRecipDesc));
      					ptr += size;
      				}
      				Marshal.FreeHGlobal(msg.recips);
      			}
      
      			if (msg.files != IntPtr.Zero)
      			{
      				size = Marshal.SizeOf(typeof(MapiFileDesc));
      
      				ptr = (int)msg.files;
      				for (int i = 0; i < msg.fileCount; i++)
      				{
      					Marshal.DestroyStructure((IntPtr)ptr,
      						typeof(MapiFileDesc));
      					ptr += size;
      				}
      				Marshal.FreeHGlobal(msg.files);
      			}
      
      			m_recipients.Clear();
      			m_attachments.Clear();
      			m_lastError = 0;
      		}
      
      		public string GetLastError()
      		{
      			if (m_lastError <= 26)
      				return errors[m_lastError];
      			return "MAPI error [" + m_lastError.ToString() + "]";
      		}
      
      		readonly string[] errors = new string[] {
              "OK [0]", "User abort [1]", "General MAPI failure [2]", 
                      "MAPI login failure [3]", "Disk full [4]", 
                      "Insufficient memory [5]", "Access denied [6]", 
                      "-unknown- [7]", "Too many sessions [8]", 
                      "Too many files were specified [9]", 
                      "Too many recipients were specified [10]", 
                      "A specified attachment was not found [11]",
              "Attachment open failure [12]", 
                      "Attachment write failure [13]", "Unknown recipient [14]", 
                      "Bad recipient type [15]", "No messages [16]", 
                      "Invalid message [17]", "Text too large [18]", 
                      "Invalid session [19]", "Type not supported [20]", 
                      "A recipient was specified ambiguously [21]", 
                      "Message in use [22]", "Network failure [23]",
              "Invalid edit fields [24]", "Invalid recipients [25]", 
                      "Not supported [26]" 
              };
      
      
      		List<MapiRecipDesc> m_recipients = new
      			List<MapiRecipDesc>();
      		List<string> m_attachments = new List<string>();
      		int m_lastError = 0;
      
      		const int MAPI_LOGON_UI = 0x00000001;
      		const int MAPI_DIALOG = 0x00000008;
      		const int maxAttachments = 20;
      
      		enum HowTo { MAPI_ORIG = 0, MAPI_TO, MAPI_CC, MAPI_BCC };
      	}
      
      	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
      	public class MapiMessage
      	{
      		public int reserved;
      		public string subject;
      		public string noteText;
      		public string messageType;
      		public string dateReceived;
      		public string conversationID;
      		public int flags;
      		public IntPtr originator;
      		public int recipCount;
      		public IntPtr recips;
      		public int fileCount;
      		public IntPtr files;
      	}
      
      	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
      	public class MapiFileDesc
      	{
      		public int reserved;
      		public int flags;
      		public int position;
      		public string path;
      		public string name;
      		public IntPtr type;
      	}
      
      	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
      	public class MapiRecipDesc
      	{
      		public int reserved;
      		public int recipClass;
      		public string name;
      		public string address;
      		public int eIDSize;
      		public IntPtr entryID;
      	}
      }
      Verwendung:
      Code:
      MAPI mapi = new MAPI();
      mapi.AddRecipientTo(recipient);
      mapi.AddAttachment(attachmentPath);
      mapi.SendMailPopup(subject, body);
      //mapi.SendMailDirect(strBetreff, strBody);
      .net-Boardmittel:
      Code:
      using System.Net;
      using System.Net.Mail;
      ...
      using (MailMessage mail = new MailMessage(from, to))
      {
      	mail.Subject = subject;
      	mail.Body = body;
      	mail.Attachments.Add(new Attachment(fileName));
      
      	SmtpClient smtp = new SmtpClient(host, port);
      	smtp.Credentials = new NetworkCredential(userName, password);
      	smtp.Send(mail);
      }
      mfG Gü
      "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

      Comment


      • #4
        Oh, das sieht aus als wäre da etwas mehr zu tun, als ich dachte...
        Hab bisher den standart email client geöffnet, und versucht diesem eine Datei zu übergeben...
        Code:
        
        privatevoid linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
        string prg = "mailto:" + linkLabel1.Text;
        string param = "C:\\Users\\Brown\\Desktop\\test.txt\\";
        System.Diagnostics.Process.Start(prg, param);
        }
        

        Comment


        • #5
          Im mailto: Protokoll gibts kein Attachment. Ist auch gut so.

          Die Email.cs kannst du ja kopieren. Der Aufruf ist dann nicht so aufwändig.
          Allerdings hab ich es mit dieser Methode (noch) nicht hinbekommen eine saubere HTML-Email für Outlook zu erstellen. Mit dem ThunderBird schon.

          mfG Gü
          "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

          Comment


          • #6
            Ok, ich habDeine Klasse jetzt mal eingefügt, und im Click Ereignis des LinkLabels, die Verwendung so:
            Code:
            string recipient = linkLabel1.Text;
            string attachmentPath = @"C:\**\**\**\test.txt@";
            string subject = "SupportRequest";
            string body = "";
            MAPI mapi = newMAPI();
            mapi.AddRecipientTo(recipient);
            mapi.AddAttachment(attachmentPath);
            mapi.SendMailPopup(subject, body);
            ich bekomme aber beim ausführen des Programms, einen Fehler, wenn ich auf das LinkLabel klicke:

            MAPISendMail failed! General MAPI failure [2]

            Liegt das am Code?

            Comment


            • #7
              Ist das ein Web-Anwendung oder WinForm.

              LinkLabel -> Web, ich dachte WinForm. Da geht MAPI natürlich nicht denn auf dem Server baucht/kann der MailClient(Outlook, Thunderbird, etc.) nicht geöffnet werden.

              Daher verwende die 2. Variante.

              mfG Gü
              "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

              Comment


              • #8
                Es handelt sich um ein Win_Form, über ein Support Form möchte ich es dem Nutzer ermöglichen eine Support Mail zu schreiben, dabei soll gleich eine Sys_dump Datei angehängt werden... Dazu soll der jeweilige standart email Client geöffnet werden. Geht das so überhaupt, oder muß der Nutzer diese Datei bei diesem Verfahren selbst anhängen?

                Comment


                • #9
                  Das geht schon so. Bei deinem obigen Code verstehe ich das @ am Ende des Pfades nicht -> gehört wohl nicht hin -> sollte dann gehen.

                  Das @ vor einem String verhindert das Escapesequenzen verarbeitet werden. Escapesequenzen werden mit einem \ eingeleitet. Deshalb ist bei (Win)-Pfadangaben dem String ein @ vorangestellt, sonst müsste der \ escaped werden. D.h.
                  Code:
                  string pfad1 = @"c:\test";
                  string pfad2 = "c:\\test";
                  
                  bool b = pfad1 == pdad2; // liefert true
                  mfG Gü
                  "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

                  Comment


                  • #10
                    Jup genau, da lag der Fehler...
                    Hab gedacht das @ muss die Pfadangabe einschließen...
                    Der oben gezeigte Code ruft jetzt den Standart Email Client auf, und öffnet eine leere Email mit Anhang...
                    Danke für die Hilfe!

                    Comment

                    Working...
                    X