Nova postagem

Pesquisar

Artigo
· Mar. 25 6min de leitura

%Net.POP3 を使用して添付ファイル付きのメールを受信する方法 --- Gmailを使用したサンプルのご紹介

以前公開している こちら の記事では、「OAuth 2.0 を利用して IRIS から Gmail を送信する」方法をご紹介しています。

本記事では、 %Net.POP3 クラスを使用してメールを受信するサンプルをご紹介します。


【事前準備(Gmailの場合)】

外部アプリからGmailを受信するには OAuth 2.0が必要となるため、こちらの手順 に従ってAccessToken を取得しておきます。
また、「2.【準備】IRIS で、SSLクライアントの設定をする : 手順(4)」の手順に従って、GMAILSSL(任意の名前)の構成を作成しておきます。


【サンプルの内容】

以下のサンプルでは、

1.Gmailの受信サーバ(servername = pop.gmail.com)に、ユーザ名(user = xxx@gmail.com)、パスワード(pass = パスワード)、AccessTokenを使用して接続し、

Set status=server.Connect(servername,user,pass,accesstoken)

2.メールボックスの情報を取得し、

Do ..ShowMailbox(server)

3.Fetch() メソッドを使用して、添付ファイルを含むメールの内容の取得し、
  (添付は server.AttachDir で指定したディレクトリに保存)

Do ..FetchMailbox(server)

4.さらに、メールの内容を表示(出力)しています。

Do DumpMessage(msg)

※3や4の処理は、不要であればコメントアウトして、メールボックスの情報のみ取得することも可能です。
 

【注意】%Net.SMTP と %Net.POP3 の OAuth 対応は、Cache2018.1.8IRIS2021.1.3 以降のバージョンとなります。



【サンプルコード:ObjectScript】

Class User.RecMail Extends %RegisteredObject
{

ClassMethod TestPOP3()
{
  Set server=##class(%Net.POP3).%New()
  set server.SSLConfiguration="GMAILSSL"
  set server.UseSTARTTLS=0
  Set server.port=995
  //Settings for retrieving messages with attachments
  Set server.StoreAttachToFile=1
  Set server.StoreInlineToFile=1
  Set server.AttachDir="C:\temp\"
  Set servername="pop.gmail.com"
  Set user=^user
  Set pass=^pass           // accesstoken を指定する場合は、パスワードは省略可能
  Set accesstoken=^accesstoken
  Set status=server.Connect(servername,user,pass,accesstoken)   // OAuthが必要ない場合、accesstokenは省略可
  If $$$ISERR(status) 
  {
    Do $System.Status.DisplayError(status) 
    Do server.QuitAndRollback()
    Quit
  }
  
  // Getting information about the Mailbox
  Do ..ShowMailbox(server)
  
  // Getting mail contents including attachment files using the Fetch() method
  Do ..FetchMailbox(server)

  Do server.QuitAndCommit()
  Quit
}

/// メールボックスの情報を取得
ClassMethod ShowMailbox(server As %Net.POP3)
{
    Set status=server.GetMailBoxStatus(.count,.size)
    If $$$ISERR(status) {
       Do $System.Status.DisplayError(status) 
       Quit
    }
    Write "Mailbox information(ShowMailbox) *****",!
    Write "Number of messages in mailbox: ",count,!
    Write "Size of messages: ",size,!

    Set status=server.GetMessageUIDArray(,.uids)
    Set status=server.GetSizeOfMessages(,.sizes)
    
    //iterate through messages, get info, and write it
    For i=1:1:count {
        Set uid=uids.GetAt(i)
        Set size=sizes.GetAt(i)
        Write "Msg number:", i,"   UID:",uid, "   size:",size,!
    }
}

/// Fetch() メソッドを使用して、添付ファイルを含むメールの内容の取得
ClassMethod FetchMailbox(server As %Net.POP3)
{
  Set status=server.GetMailBoxStatus(.count,.size)
  If $$$ISERR(status) {
    Do $System.Status.DisplayError(status) 
    Quit
  }
  Write !,"Mailbox information(FetchMailbox) *****",!
  Write "Number of messages in mailbox: ",count,!
  Write "Size of messages: ",size,!

  Set status=server.GetMessageUIDArray(,.uids)
  Set status=server.GetSizeOfMessages(,.sizes)
  
  //iterate through messages, get info, and write it
  For i=1:1:count {
    Set uid=uids.GetAt(i)
    Set size=sizes.GetAt(i)
    Set status=server.Fetch(i,.msg)  // 第3引数に 1 を指定すると、処理後にメッセージを削除する
    If $$$ISERR(status) {
      Do $System.Status.DisplayError(status)
      Set subj="***error***"
      Quit
    } else{
      Set subj=msg.Subject
    }
    Write !,!,"=================================================",!
    Write "Msg number:", i,"  UID:",uid, "  Size:",size
    Write "  Subject: ",subj,!
    Write "From: "_msg.From,!
    Write "Date: "_msg.Date,!
    
    /*--- To view the contents of emails ---*/
    Do ..DumpMessage(msg)

  }
}

/// メールの内容を表示(出力)
ClassMethod DumpMessage(msg As %Net.MailMessagePart)
{
    write "-------------------------",!
    if msg.IsMultiPart {
        for i=1:1:msg.Parts.Count() {
            write !,"[Dumping part "_i,"]",!
            do ..DumpMessage(msg.Parts.GetAt(i))
        }
    } 
    else {
        write "ContentType=",msg.ContentType,!!
        //----- Binary -----
        if msg.IsBinary {
            if msg.FileName="" {
                set stream=msg.BinaryData
                do stream.Rewind()
                for  set len=32763 quit:stream.AtEnd  Write stream.Read(.len)
            } else {              //----------------- Attached File
                write "Attached File Name(Binary):"_msg.FileName,!
            }
        //----- Text -----				
        } else {
            if msg.FileName="" {
                set stream=msg.TextData
                do stream.Rewind()
                for  set len=32763 quit:stream.AtEnd  Write stream.Read(.len)
            } else {              //----------------- Attached File
                write "Attached File Name(Text):"_msg.FileName,!
            }
        }
    }
}

}


どんな出力になるのか、ターミナルで実行したサンプルの出力例をご紹介します。

以下は、2通のメールの受信例で、それぞれテキストとバイナリの添付ファイルを受信しています。

USER>do ##class(User.RecMail).TestPOP3()
Mailbox information *****
Number of messages in mailbox: 2
Size of messages: 29095
Msg number:1   UID:GmailId195cbf0bf4fc2799   size:15195
Msg number:2   UID:GmailId195cbf0fb0ed8cde   size:13900
Mailbox information *****
Number of messages in mailbox: 2
Size of messages: 29095
=================================================
Msg number:1  UID:GmailId195c  Size:15195  Subject: テキストを添付
From: xxx <xxx@InterSystems.com>
Date: Tue, 25 Mar 2025 06:15:02 +0000
-------------------------

[Dumping part 1]
-------------------------
ContentType=text/plain

Start
あいうえお
かきくけこ
さしすせそ
End


[Dumping part 2]
-------------------------
ContentType=text/plain

Attached File Name(Text):note.txt


=================================================
Msg number:2  UID:GmailId195c  Size:13900  Subject: Binaryを添付
From: xxx <xxx@InterSystems.com>
Date: Tue, 25 Mar 2025 06:15:19 +0000
-------------------------

[Dumping part 1]
-------------------------
ContentType=text/plain

Aaaaa
Bbbbb
Ccccc
Ddddd


[Dumping part 2]
-------------------------
ContentType=application/octet-stream

Attached File Name(Binary):test2.csv

USER>


添付ファイルは以下のディレクトリに保存されています。



詳細は以下のドキュメントをご覧ください。
POP3 を介した電子メールの取得

Discussão (0)0
Entre ou crie uma conta para continuar
Pergunta
· Mar. 25

AWS Files

Hi Guys,

I'm looking to create a service to download files from S3, so I used the EnsLib.AmazonS3.BusinessService with settings as below to download files that starts with SMfile_48 but I'm not getting any files, am I missing something?

 

 

 

Thanks

1 Comment
Discussão (1)1
Entre ou crie uma conta para continuar
Anúncio
· Mar. 24

Reminder: Beta Testers Needed for Our Upcoming InterSystems IRIS Developer Professional Certification Exam

Hello again IRIS community,

We have officially released our InterSystems IRIS Developer Professional certification exam for beta testing. The beta test will be available until April 20, 2025. As a beta tester, you have the chance to earn the certification for free!

Interested in beta testing? See the InterSystems IRIS Developer Professional Beta Test Developer Community post for exam details, recommended preparation, and instructions on how to schedule and take the beta exam. 

Thank you!

Discussão (0)1
Entre ou crie uma conta para continuar
Resumo
· Mar. 24

Publicações Desenvolvedores InterSystems, Março 17 - 23, 2025, Resumo

Artigos
Anúncios
#InterSystems IRIS
#Outro
#Developer Community Oficial
Aviso de manutenção planejada
Por Anastasia Dyubaylo
Março 17 - 23, 2025Week at a GlanceInterSystems Developer Community
Resumo
· Mar. 24

InterSystems Developers Publications, Week March 17 - 23, 2025, Digest

Articles
Announcements
#InterSystems IRIS
#IRIS contest
#Other
#Job Wanted
#Learning Portal
#Developer Community Official
Planned Maintenance Notice
By Anastasia Dyubaylo
#InterSystems IRIS for Health
Questions
#InterSystems IRIS
#InterSystems IRIS for Health
Discussions
March 17 - 23, 2025Week at a GlanceInterSystems Developer Community