Search code examples
c#mailmessage

MailMessage properties not accepting parameter variables


For some reason, when trying to initialize the properties From, Subject, and Body for a MailMessage object I can't use variables from the method parameters.

Ex - Doesn't work:

public static void MailToEML(String email, String subj, String body)
{
    MailMessage mailMessage = new MailMessage
    {
        From = new MailAddress(email),
        Subject = subj,
        Body = body
    };

(Rest of method irrelevant)

Ex - Works

public static void MailToEML()
{
    String email = "[email protected]";
    String subj = "Subject";
    String body = "Contents";

    MailMessage mailMessage = new MailMessage
    {
        From = new MailAddress(email),
        Subject = subj,
        Body = body
    };

I've tried with List<String>, String[], and String parameters, none of them seem to work, but when they are initialized inside the method, it works flawlessly.

Error when trying with parameters:

System.FormatException: 'The specified string is not in the form required for an e-mail address.'

FIXED: Similarily, if From is correct, Subject will output the same error message, and same with Body. Solution: Appended a \n to Subject somewhere else in the code, which the formatting did not agree with, so I just had to remove that

Calling method:

public void ExportClicked(Office.IRibbonControl control)
{
    Object selObject = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];

    Outlook.MailItem mailItem =
        (selObject as Outlook.MailItem);

    String email;
    String subject;
    String body;

    email = mailItem.SenderEmailAddress;
    subject = mailItem.Subject;
    body = mailItem.Body;

    if (mailItem.Subject == null)
    {
        subject = ThisAddIn.lang[1]; //Array element determines language, not important here
    }

    ThisAddIn.MailToEML(email, subject, body);

}

(Just want to mention that I will be making these an array or list if I find a solution)


Solution

  • After searching around for a while, I figured out I was making this a lot more complicated than it really was. Instead of several string values, I used a MailItem object.

    This is the new MailToEml() method:

    public static void MailToEML(Outlook.MailItem mail)
    {
        MailMessage mailMessage = new MailMessage
        {
            From = new MailAddress(mail.SenderEmailAddress),
            SubjectEncoding = System.Text.Encoding.UTF8,
            Subject = mail.Subject,
            Body = mail.Body
        };