관리 메뉴

미래 개발 연구소

[C#] Outlook 메일 보내기 본문

C#/Office

[C#] Outlook 메일 보내기

쓰봥 2022. 2. 27. 01:06
SMALL

이번에는 C# 프로그램 내에서 Outlook 메일을 보내는 기능을 다뤄보자.

 

개발환경

  • Microsoft.Office.Interop.Outlook 15.0.0.0
  • .NET Framework 4.5
  • Windows 10

 

목적

  1.  응용 프로그램 내에서 Outlook 을 통하여 지정한 상대방에게 메일을 보내고자 한다.

using Outlook = Microsoft.Office.Interop.Outlook;

//Outlook Application 객체 생성
Outlook.Application oApp = new Outlook.Application();

//Outlook MailItem 에 대한 객체 생성
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

//메일 제목
oMsg.Subject = "메일 송부 기능";

//메일에 담을 내용.
oMsg.Body = "Outlook 메일 송부하기";

//첨부파일 경로.
oMsg.Attachments.Add(save_file_path);

//받는사람 지정
oMsg.To = "dlf@naver.com";

//임시 저장
oMsg.Save();

//Outlook 가시화
oMsg.Display(false);

//메일 전송
//oMsg.Send();

 

우선 기본적인 Outlook 메일 아이템에 대한 구성요소는 다 채워졌다.

간단하게 설명을 하고 넘어가면, Outlook Application 에 대한 객체를 선언하고,

Outlook Application 에서 MailItem 객체를 생성한다. 

여기까지가 Outlook 에서 '새 전자 메일' 버튼을 클릭하는 것과 같다고 생각하면 된다.

 

그리고 MailItem 에 Subject(메일 제목) 요소 , Body(메일 내용), Attachments(첨부파일),

To(받는 사람) 을 채워 주면 메일을 전송 하기 직전단계까지 완성되었다.

 

그리고 메일을 저장하고, Display 해 주면

앞에서 작성한 내용이 포함된 Outlook 메일 전송 창이 뜨게 된다.

만약 메일을 확인 하지 않고 바로 보내고 싶다면 Send를 이용해 바로 전송하면 된다.

 

하지만, 여기서 내 눈에는 살짝 거슬리는 부분이 발생한다.

만약 내 Outlook 주소록에 지금 받는 사람메일 주소인

'dlf@naver.com' 이 '홍길동' 이라는 이름으로 주소록에 저장되어 있는데,

실제로 받은 메일에 보면, 받는사람에 'dlf@naver.com' 으로 표기 된다.

 

해당 기능을 통하지 않고 그냥 메일을 작성해서 받는사람을 주소록에서 선택하게 되면

받는 사람 에는 '홍길동' 이라고 뜨는데, 기능을 통해서 보내면 그렇게 되지 않는다.

 

그냥 이렇게 써도 무방하지만 누가 보냈는지, 누구에게 보냈는지 한눈에 확인이

어려울 수도 있고, 무엇보다도 내 눈에 거슬린다.

 

그래서 이번에는, 현재 내 PC 에 설치된 Outlook 의 주소록을 확인해서, 

'dlf@naver.com' 이라는 주소록이 저장되 있을 경우, 그 사람 이름으로 보내는 내용을

추가해 보려고 한다.

 

string contactMessage = string.Empty;
Outlook.ContactItem foundContact;

//주소록 정보.
Outlook.MAPIFolder contacts = (Outlook.MAPIFolder)oApp.Session.GetDefaultFolder
    (Outlook.OlDefaultFolders.olFolderContacts);

List<Outlook.ContactItem> itemList = new List<Outlook.ContactItem> { };

//기본 주소록 정보.
foreach (var contact in contacts.Items)
{
    if (contact is Outlook.ContactItem)
    {
        foundContact = contact as Outlook.ContactItem;
        if (foundContact.Email1Address != null)
        {
            itemList.Add(foundContact);
        }
    }
}

//폴더로 묶인 주소록 정보.
foreach (Outlook.MAPIFolder address_folder in contacts.Folders)
{
    foreach (var contact in address_folder.Items)
    {
        if (contact is Outlook.ContactItem)
        {
            foundContact = contact as Outlook.ContactItem;
            if (foundContact.Email1Address != null)
            {
                itemList.Add(foundContact);
            }
        }
    }
}

Dictionary<string, string> mailNameDic = new Dictionary<string, string> { };

string mail = "dlf@naver.com";

mailNameDic[mail] = string.Empty;

foreach (Outlook.ContactItem item in itemList)
{
    if (item.Email1Address.Contains(mail))
    {
        string display_name = item.Email1DisplayName;
        mailNameDic[mail] = display_name;
    }
}

string receive = string.Empty;

int cnt = 0;
foreach (string key in mailNameDic.Keys)
{
    string display_name = mailNameDic[key];
    if (display_name == string.Empty)
        display_name = key;

    if (cnt == 0)
        receive = display_name + "; ";
    else
        receive = receive + display_name + "; ";

    cnt++;
}

//받는사람 지정
oMsg.To = receive;

이렇게, 현재 내 PC 에 저장된 Outlook 의 주소록에서, 내가 보내고자 하는 메일주소가

저장되어 있을 경우, 표시 이름을 대신 표기 하여 메일을 보내도록 구성해 보았다.

 

위의 내용도 크게 별거 없는게, 우리가 Outlook 에서 주소록에 주소를 등록 해 두고, 

받는 사람을 지정할때, 저장된 사람 이름만 작성해도, 받는 사람의 메일로 전송이 된다.

 

여기도 마찬가지로, 내가 보내고자 하는 메일주소가 등록되어 있는지 확인하고,

등록이 되어 있다면, 그 사람의 이름을 받는 사람 에 적어주는 것 뿐이다.

 

기회가 된다면, 다음번엔 Outlook의 VSTO 기능에 대해 다뤄볼 예정이니

이 글을 읽고 관심 있는 사람은 참고 하면 될거 같다.

 

이상.

 


[전체 소스]

 

//Outlook Application 객체 생성
Outlook.Application oApp = new Outlook.Application();

//Outlook MailItem 에 대한 객체 생성
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

//메일 제목
oMsg.Subject = "메일 송부 기능";

//메일에 담을 내용.
oMsg.Body = "Outlook 메일 송부하기";

//첨부파일 경로.
//oMsg.Attachments.Add(save_file_path);

string contactMessage = string.Empty;
Outlook.ContactItem foundContact;

//주소록 정보.
Outlook.MAPIFolder contacts = (Outlook.MAPIFolder)oApp.Session.GetDefaultFolder
    (Outlook.OlDefaultFolders.olFolderContacts);

List<Outlook.ContactItem> itemList = new List<Outlook.ContactItem> { };

//기본 주소록 정보.
foreach (var contact in contacts.Items)
{
    if (contact is Outlook.ContactItem)
    {
        foundContact = contact as Outlook.ContactItem;
        if (foundContact.Email1Address != null)
        {
            itemList.Add(foundContact);
        }
    }
}

//폴더로 묶인 주소록 정보.
foreach (Outlook.MAPIFolder address_folder in contacts.Folders)
{
    foreach (var contact in address_folder.Items)
    {
        if (contact is Outlook.ContactItem)
        {
            foundContact = contact as Outlook.ContactItem;
            if (foundContact.Email1Address != null)
            {
                itemList.Add(foundContact);
            }
        }
    }
}

Dictionary<string, string> mailNameDic = new Dictionary<string, string> { };

string mail = "dlf@naver.com";

mailNameDic[mail] = string.Empty;

foreach (Outlook.ContactItem item in itemList)
{
    if (item.Email1Address.Contains(mail))
    {
        string display_name = item.Email1DisplayName;
        mailNameDic[mail] = display_name;
    }
}

string receive = string.Empty;

int cnt = 0;
foreach (string key in mailNameDic.Keys)
{
    string display_name = mailNameDic[key];
    if (display_name == string.Empty)
        display_name = key;

    if (cnt == 0)
        receive = display_name + "; ";
    else
        receive = receive + display_name + "; ";

    cnt++;
}

//받는사람 지정
oMsg.To = receive;

//임시 저장
oMsg.Save();

//Outlook 가시화
oMsg.Display(false);

//메일 전송
//oMsg.Send();