Mail은 이메일 생성, 구문 분석 및 간단하고 루비즈 같은 방식으로 보내도록 설계된 Ruby의 인터넷 라이브러리입니다.
이 라이브러리의 목적은 이메일 보내기 및 수신을 포함하여 모든 이메일 기능을 처리하기위한 단일 액세스 지점을 제공하는 것입니다. 모든 네트워크 유형 조치는 프록시 메소드를 통해 Net :: SMTP, NET :: POP3 등으로 수행됩니다.
Tmail에 대한 나의 경험을 통해 구축 된이 제품은 이메일을 생성, 전송 및 구문 분석하는 순수한 루비 구현으로 설계되었습니다.
또한보다 현대적인 버전의 Ruby와 함께 작업하도록 처음부터 설계되었습니다. 현대 루비는 텍스트 인코딩을 전보다 훨씬 더 훌륭하게 처리하므로 이러한 기능을이 라이브러리에서 최대한 활용하여 메일이 Tmail보다 더 깨끗하게 더 많은 메시지를 처리 할 수 있습니다.
마지막으로, Mail은 매우 간단한 객체 지향 시스템으로 설계되어 구문 분석중인 이메일 메시지를 실제로 열어줍니다. 수행중인 작업을 알고 있다면 이메일의 모든 마지막 비트를 직접 바이올린 할 수 있습니다.
네, 당신! 메일은 전 세계 사람들의 수많은 앱에서 사용됩니다. 그것은 모든 오픈 소스 소프트웨어와 마찬가지로 자유 시간에서 시작된 사랑의 노동입니다. 당신이 감사하다고 말하고 싶다면, 우리와 함께 파고 들고 기여하십시오! 심사 및 수정 GitHub 문제, 문서를 개선하고 새로운 기능을 추가하십시오. 투구 해주셔서 감사합니다.
메일은 다음에 대해 테스트됩니다.
새로운 버전의 Ruby가 출시되면 Mail은 "미리보기"및 모든 "정상 유지 관리", "보안 유지 관리"및 Ruby Maintenance Branches 페이지에 나열된 가장 최근의 "End of Life"버전을 지원하는 것과 호환됩니다. 새로운 미리보기 릴리스에 대한 지원을 추가하는 데 도움이되는 풀 요청은 환영합니다.
모든 메일 커밋은 모든 지원되는 루비 버전에서 Github 조치로 테스트됩니다.
마인드 마인드 개인과 메일에 대해 토론하려면 Google 그룹에 가입하십시오.
Mail은 RFC5322 및 RFC6532를 준수합니다. 즉, US-ASCII 및 UTF-8 이메일을 구문 분석하고 US-ASCII 이메일을 생성 할 수 있습니다. 문제가있는 몇 가지 쓸모없는 이메일 구문이 있지만, 또한 매우 강력합니다. 의미가없는 것을 발견하면 충돌하지 않을 것이라는 것을 알면 문제를 건너 뛰고 구문 분석을 유지합니다. 헤더의 경우 이해하지 못하면 헤더를 옵션의 비정형 필드로 초기화하고 계속 구문 분석합니다.
즉, Mail이 데이터를 크롤링하지 않을 것임을 의미합니다 (생각합니다).
MIME 이메일을 만들 수도 있습니다. Text/Plain 및 Text/HTML (가장 일반적인 쌍) 용 Multipart/Alternate 이메일을 만드는 도우미 방법이 있으며 다른 유형의 Mime 이메일을 수동으로 만들 수 있습니다.
다음 Todo :
기본적으로 ... 우리는 우편으로 BDD를합니다. 해당 또는 커버링 사양없이 메소드가 우편으로 작성되지 않습니다. 우리는 RCOV에서 측정 한 최소 100% 적용 범위를 기대합니다. 이것은 어떤 측정도 완벽하지는 않지만 꽤 좋습니다. 또한 Tmail의 모든 기능 테스트는 보석이 풀리기 전에 통과해야합니다.
또한 메일이 올바르게 행동 할 수 있음을 의미합니다.
bundle exec rspec
실행하여 테스트를 로컬로 실행할 수 있습니다.
ACT를 사용하여 지원되는 모든 Ruby 버전에서 테스트를 실행할 수 있습니다.
단일 포인트 릴리스 내에 API 제거가 없습니다. 모든 제거는 제거 전에 적어도 하나의 사소한 포인트 방출에 대한 경고로 더 이상 사용되지 않습니다.
또한, 모든 개인 또는 보호 된 방법은 그렇게 선언되어야합니다.
설치는 상당히 간단합니다. 저는 RubyGems에서 메일을 호스팅하므로 다음과 같이 할 수 있습니다.
# gem install mail
모르는 경우 이메일로 인코딩을 처리하는 것이 원하는만큼 간단하지 않습니다.
나는 그것을 단순화하려고 노력했다.
이메일로 렌더링 할 수있는 모든 객체에는 #encoded
메소드가 있습니다. Encoded는 메일 시스템을 보낼 준비가 된 완전한 문자열로 객체를 반환합니다. 즉, 헤더 필드와 값 및 마지막에 CRLF가 포함되어 필요에 따라 포장됩니다.
이메일로 렌더링 할 수있는 모든 객체에는 #decoded
메소드가 있습니다. 디코딩 된 것은 객체의 "값"을 문자열로만 반환합니다. 즉, 헤더 필드가 포함되지 않음을 의미합니다 (예 : 'to :'또는 'subject :').
기본적으로 컨테이너 객체에서 #to_s
호출하면 인코딩 된 메소드를 호출하고 필드 객체의 #to_s
해독 된 메소드를 호출합니다. 따라서 메일 객체에서 #to_s
호출하면 메일을 반환하고, 모두 인코딩 된 인코딩 된 모든 것을 보내고, From Find에서 #to_s
호출하거나 본체는 객체의 디코딩 된 값을 반환합니다. 메일의 헤더 객체는 컨테이너로 간주됩니다. 의심스러운 경우, #encoded
또는 #decoded
로 전화하십시오. 확실하지 않은 경우 더 안전합니다.
인코딩 할 수있는 매개 변수 값 (예 : 컨텐츠 유형)을 갖는 구조화 된 필드는 객체에 대한 메소드로 매개 변수 이름을 호출 할 때 디코딩 된 매개 변수 값을 제공합니다.
인코딩 될 수있는 매개 변수 값 (예 : Content-Type)을 갖는 구조화 된 필드는 object.parameters['<parameter_name>']
메소드 호출을 통해 매개 변수 이름을 호출 할 때 인코딩 된 매개 변수 값을 제공합니다.
제발! 기여는 우편으로 쉽습니다. 자세한 내용은 Contributing.md 문서를 읽으십시오.
모든 주요 우편 기능은 메일 모듈에서 발생할 수 있어야합니다. 따라서 시작하려면 require 'mail'
수 있어야합니다.
mail
루비 코드로 잘 문서화되어 있습니다. Rubydoc.info에서 예를 들어 볼 수 있습니다.
mail = Mail . new do
from '[email protected]'
to '[email protected]'
subject 'This is a test email'
body File . read ( 'body.txt' )
end
mail . to_s #=> "From: [email protected]: you@...
mail = Mail . new do
body File . read ( 'body.txt' )
end
mail [ 'from' ] = '[email protected]'
mail [ :to ] = '[email protected]'
mail . subject = 'This is a test email'
mail . header [ 'X-Custom-Header' ] = 'custom value'
mail . to_s #=> "From: [email protected]: you@...
mail = Mail . new do
to '[email protected]'
body 'Some simple body'
end
mail . to_s =~ /Message - ID: <[ d w _]+@.+.mail/ #=> 27
Mail이 누락 된 경우 Mail-ID 필드를 자동으로 추가하고 다음의 줄을 따라 독특하고 임의의 메시지를 제공합니다.
mail = Mail . new do
to '[email protected]'
message_id '<[email protected]>'
body 'Some simple body'
end
mail . to_s =~ /Message - ID: <[email protected]>/ #=> 27
Mail은 당신이 무엇을하고 있는지 알고 있다는 것을 믿기 위해 당신이 할당하는 message_id를 가져갑니다.
메일 기본값은 SMTP를 통해 로컬 호스트 포트로 전송하는 기본값 25입니다.
Mail . deliver do
from '[email protected]'
to '[email protected]'
subject 'Here is the image you wanted'
body File . read ( 'body.txt' )
add_file '/full/path/to/somefile.png'
end
또는
mail = Mail . new do
from '[email protected]'
to '[email protected]'
subject 'Here is the image you wanted'
body File . read ( 'body.txt' )
add_file :filename => 'somefile.png' , :content => File . read ( '/somefile.png' )
end
mail . deliver!
Sendmail을 통해 보내는 것은 그렇게 할 수 있습니다.
mail = Mail . new do
from '[email protected]'
to '[email protected]'
subject 'Here is the image you wanted'
body File . read ( 'body.txt' )
add_file :filename => 'somefile.png' , :content => File . read ( '/somefile.png' )
end
mail . delivery_method :sendmail
mail . deliver
SMTP를 통해 보내기 (예 : MailCatcher로)
Mail . defaults do
delivery_method :smtp , address : "localhost" , port : 1025
end
Exim은 자체 배송 관리자가 필요하며 그렇게 사용할 수 있습니다.
mail . delivery_method :exim , :location => "/usr/bin/exim"
mail . deliver
개발 및 테스트를 위해 메일도 로그 파일로 "전달"될 수 있습니다.
# Delivers by logging the encoded message to $stdout
mail . delivery_method :logger
# Delivers to an existing logger at :debug severity
mail . delivery_method :logger , logger : other_logger , severity : :debug
Mail.defaults
내에서 retriever_method
사용하여 이메일을 수신하도록 메일을 구성 할 수 있습니다.
# e.g. POP3
Mail . defaults do
retriever_method :pop3 , :address => "pop.gmail.com" ,
:port => 995 ,
:user_name => '<username>' ,
:password => '<password>' ,
:enable_ssl => true
end
# IMAP
Mail . defaults do
retriever_method :imap , :address => "imap.mailbox.org" ,
:port => 993 ,
:user_name => '<username>' ,
:password => '<password>' ,
:enable_ssl => true
end
여러 가지 방법으로 들어오는 이메일에 액세스 할 수 있습니다.
가장 최근의 이메일 :
Mail . all #=> Returns an array of all emails
Mail . first #=> Returns the first unread email
Mail . last #=> Returns the last unread email
날짜별로 오름차순 순서로 정렬 된 첫 10 개의 이메일 :
emails = Mail . find ( :what => :first , :count => 10 , :order => :asc )
emails . length #=> 10
또는 모든 이메일 :
emails = Mail . all
emails . length #=> LOTS!
mail = Mail . read ( '/path/to/message.eml' )
mail . envelope_from #=> '[email protected]'
mail . from . addresses #=> ['[email protected]', '[email protected]']
mail . sender . address #=> '[email protected]'
mail . to #=> '[email protected]'
mail . cc #=> '[email protected]'
mail . subject #=> "This is the subject"
mail . date . to_s #=> '21 Nov 1997 09:55:06 -0600'
mail . message_id #=> '<[email protected]>'
mail . decoded #=> 'This is the body of the email...
더 많은 방법을 사용할 수 있습니다.
mail = Mail . read ( 'multipart_email' )
mail . multipart? #=> true
mail . parts . length #=> 2
mail . body . preamble #=> "Text before the first part"
mail . body . epilogue #=> "Text after the last part"
mail . parts . map { | p | p . content_type } #=> ['text/plain', 'application/pdf']
mail . parts . map { | p | p . class } #=> [Mail::Message, Mail::Message]
mail . parts [ 0 ] . content_type_parameters #=> {'charset' => 'ISO-8859-1'}
mail . parts [ 1 ] . content_type_parameters #=> {'name' => 'my.pdf'}
메일은 부품의 나무를 생성합니다. 각 메시지에는 부품이 많거나 전혀 없습니다. 각 부분은 부품이 많거나 없을 수있는 또 다른 메시지입니다.
메시지는 다중 공사/혼합 또는 멀티 파트/관련 콘텐츠 유형이고 경계가 정의 된 경우에만 부품이 있습니다.
mail . attachments . each do | attachment |
# Attachments is an AttachmentsList object containing a
# number of Part objects
if ( attachment . content_type . start_with? ( 'image/' ) )
# extracting images for example...
filename = attachment . filename
begin
File . open ( images_dir + filename , "w+b" , 0644 ) { | f | f . write attachment . decoded }
rescue => e
puts "Unable to save data for #{ filename } because #{ e . message } "
end
end
end
메일은 몇 가지 기본 가정을 만들고 가능한 한 공통된 일을 단순하게 만듭니다 .... (메일 라이브러리에서 많은 것을 묻습니다)
mail = Mail . deliver do
part :content_type => "multipart/mixed" do | p1 |
p1 . part :content_type => "multipart/related" do | p2 |
p2 . part :content_type => "multipart/alternative" ,
:content_disposition => "inline" do | p3 |
p3 . part :content_type => "text/plain; charset=utf-8" ,
:body => "Here is the attachment you wanted n "
p3 . part :content_type => "text/html; charset=utf-8" ,
:body => "<h1>Funky Title</h1><p>Here is the attachment you wanted</p> n "
end
end
add_file '/path/to/myfile.pdf'
end
from "Mikel Lindsaar <[email protected]>"
to "[email protected]"
subject "First multipart email sent with Mail"
end
그런 다음 메일은 블록 끝에서 이메일을 전달하고 결과 메일 :: 메시지 개체를 반환합니다. 그러면 원하는지 확인할 수 있습니다 ...
puts mail.to_s #=>
Date: Tue, 26 Apr 2022 20:12:07 +0200
From: Mikel Lindsaar <[email protected]>
To: [email protected]
Message-ID: <[email protected]>
Subject: First multipart email sent with Mail
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="--==_mimepart_626835f733867_10873fdfa3c2ffd494636";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_626835f733867_10873fdfa3c2ffd494636
Content-Type: multipart/mixed;
boundary="--==_mimepart_626835f73382a_10873fdfa3c2ffd494518";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_626835f73382a_10873fdfa3c2ffd494518
Content-Type: multipart/related;
boundary="--==_mimepart_626835f7337f5_10873fdfa3c2ffd494438";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438
Content-Type: multipart/alternative;
boundary="--==_mimepart_626835f733702_10873fdfa3c2ffd494376";
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Content-ID: <[email protected]>
----==_mimepart_626835f733702_10873fdfa3c2ffd494376
Content-Type: text/plain;
charset=utf-8
Content-Transfer-Encoding: 7bit
Here is the attachment you wanted
----==_mimepart_626835f733702_10873fdfa3c2ffd494376
Content-Type: text/html;
charset=utf-8
Content-Transfer-Encoding: 7bit
<h1>Funky Title</h1><p>Here is the attachment you wanted</p>
----==_mimepart_626835f733702_10873fdfa3c2ffd494376--
----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438--
----==_mimepart_626835f73382a_10873fdfa3c2ffd494518--
----==_mimepart_626835f733867_10873fdfa3c2ffd494636
Content-Type: text/plain;
charset=UTF-8;
filename=myfile.txt
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename=myfile.txt
Content-ID: <6
[email protected]>
Hallo,
Test
End
----==_mimepart_626835f733867_10873fdfa3c2ffd494636--
메일은 컨텐츠 전송 인코딩, MIME 버전, 컨텐츠 -ID를 삽입하고 컨텐츠 유형 및 경계를 삽입합니다.
Mail은 신체의 텍스트가 US-ASCII에 불과한 경우 전송 인코딩이 7 비트이고 텍스트/일반이라고 가정합니다. 명시 적으로 선언하여 이것을 무시할 수 있습니다.
텍스트와 HTML 부분이 포함 된 블록을 사용할 필요가 없으므로 선언적으로 수행 할 수 있습니다. 그러나 Mail :: 메시지가 아닌 이메일에 메일 :: 부품을 추가해야합니다.
mail = Mail . new do
to '[email protected]'
from 'Mikel Lindsaar <[email protected]>'
subject 'First multipart email sent with Mail'
end
text_part = Mail :: Part . new do
body 'This is plain text'
end
html_part = Mail :: Part . new do
content_type 'text/html; charset=UTF-8'
body '<h1>This is HTML</h1>'
end
mail . text_part = text_part
mail . html_part = html_part
블록 양식을 사용하여 수행 한 것과 동일한 이메일을 제공합니다.
@mail = Mail . read ( '/path/to/bounce_message.eml' )
@mail . bounced? #=> true
@mail . final_recipient #=> rfc822;[email protected]
@mail . action #=> failed
@mail . error_status #=> 5.5.0
@mail . diagnostic_code #=> smtp;550 Requested action not taken: mailbox unavailable
@mail . retryable? #=> false
절대 경로에서 파일을 읽을 수 있습니다. Mail은 MIME_TYPE를 추측하려고 시도하고 Base64에서 파일을 인코딩합니다.
@mail = Mail . new
@mail . add_file ( "/path/to/file.jpg" )
@mail . parts . first . attachment? #=> true
@mail . parts . first . content_transfer_encoding . to_s #=> 'base64'
@mail . attachments . first . mime_type #=> 'image/jpg'
@mail . attachments . first . filename #=> 'file.jpg'
@mail . attachments . first . decoded == File . read ( '/path/to/file.jpg' ) #=> true
또는 file_data를 전달하고 파일 이름을 줄 수 있습니다. 다시, Mail은 MIME_TYPE를 추측하고 추측합니다.
@mail = Mail . new
@mail . attachments [ 'myfile.pdf' ] = File . read ( 'path/to/myfile.pdf' )
@mail . parts . first . attachment? #=> true
@mail . attachments . first . mime_type #=> 'application/pdf'
@mail . attachments . first . decoded == File . read ( 'path/to/myfile.pdf' ) #=> true
메일보다 실제로 더 잘 알고 있다면 무의미한 MIME 미디어 유형을 무시할 수 있습니다 (거의 필요하지 않아야합니다).
@mail = Mail . new
@mail . attachments [ 'myfile.pdf' ] = { :mime_type => 'application/x-pdf' ,
:content => File . read ( 'path/to/myfile.pdf' ) }
@mail . parts . first . mime_type #=> 'application/x-pdf'
물론 ... 메일이 왕복 첨부 파일도 마찬가지입니다.
@mail = Mail . new do
to '[email protected]'
from 'Mikel Lindsaar <[email protected]>'
subject 'First multipart email sent with Mail'
text_part do
body 'Here is the attachment you wanted'
end
html_part do
content_type 'text/html; charset=UTF-8'
body '<h1>Funky Title</h1><p>Here is the attachment you wanted</p>'
end
add_file '/path/to/myfile.pdf'
end
@round_tripped_mail = Mail . new ( @mail . encoded )
@round_tripped_mail . attachments . length #=> 1
@round_tripped_mail . attachments . first . filename #=> 'myfile.pdf'
자세한 내용은 위의 "테스트 및 추출"을 참조하십시오.
메일이 시스템의 일부인 경우 실제로 이메일을 보내지 않고 테스트하는 방법이 필요합니다. 테스트 메일러가이를 수행 할 수 있습니다.
require 'mail'
=> true
Mail . defaults do
delivery_method :test
end
=> #<Mail::Configuration:0x19345a8 @delivery_method=Mail::TestMailer>
Mail :: TestMailer . deliveries
=> [ ]
Mail . deliver do
to '[email protected]'
from '[email protected]'
subject 'testing'
body 'hello'
end
=> #<Mail::Message:0x19284ec ...
Mail :: TestMailer . deliveries . length
=> 1
Mail :: TestMailer . deliveries . first
=> #<Mail::Message:0x19284ec ...
Mail :: TestMailer . deliveries . clear
=> [ ]
Doota의 ActionMailer Matchers에서 도난/영감을받은 RSPEC 매치 업체 세트도 있습니다 (위와 같이 delivery_method
설정하려면).
Mail . defaults do
delivery_method :test # in practice you'd do this in spec_helper.rb
end
RSpec . describe "sending an email" do
include Mail :: Matchers
before ( :each ) do
Mail :: TestMailer . deliveries . clear
Mail . deliver do
to [ '[email protected]' , '[email protected]' ]
from '[email protected]'
subject 'testing'
body 'hello'
end
end
it { is_expected . to have_sent_email } # passes if any email at all was sent
it { is_expected . to have_sent_email . from ( '[email protected]' ) }
it { is_expected . to have_sent_email . to ( '[email protected]' ) }
# can specify a list of recipients...
it { is_expected . to have_sent_email . to ( [ '[email protected]' , '[email protected]' ] ) }
# ...or chain recipients together
it { is_expected . to have_sent_email . to ( '[email protected]' ) . to ( '[email protected]' ) }
it { is_expected . to have_sent_email . with_subject ( 'testing' ) }
it { is_expected . to have_sent_email . with_body ( 'hello' ) }
# Can match subject or body with a regex
# (or anything that responds_to? :match)
it { is_expected . to have_sent_email . matching_subject ( /test(ing)?/ ) }
it { is_expected . to have_sent_email . matching_body ( /h(a|e)llo/ ) }
# Can chain together modifiers
# Note that apart from recipients, repeating a modifier overwrites old value.
it { is_expected . to have_sent_email . from ( '[email protected]' ) . to ( '[email protected]' ) . matching_body ( /hell/ )
# test for attachments
# ... by specific attachment
it { is_expected . to have_sent_email . with_attachments ( my_attachment ) }
# ... or any attachment
it { is_expected . to have_sent_email . with_attachments ( any_attachment ) }
# ... or attachment with filename
it { is_expected . to have_sent_email . with_attachments ( an_attachment_with_filename ( 'file.txt' ) ) }
# ... or attachment with mime_type
it { is_expected . to have_sent_email . with_attachments ( an_attachment_with_mime_type ( 'application/pdf' ) ) }
# ... by array of attachments
it { is_expected . to have_sent_email . with_attachments ( [ my_attachment1 , my_attachment2 ] ) } #note that order is important
#... by presence
it { is_expected . to have_sent_email . with_any_attachments }
#... or by absence
it { is_expected . to have_sent_email . with_no_attachments }
end
사양/고정물/이메일/from_trec_2005의 사양 고정 파일은 2005 Trec Public Spam Corpus에서 나온 것입니다. 해당 프로젝트 및 라이센스 계약의 조건에 따라 저작권을 유지합니다. 이 프로젝트 에서이 이메일 파서 구현의 개발을 확인하고 설명하는 데 사용됩니다.
http://plg.uwaterloo.ca/~gvcormac/treccorpus/
'허용 된 용도, 3 항'에 의해 허용 된대로 사용됩니다.
"Small excerpts of the information may be displayed to others
or published in a scientific or technical context, solely for
the purpose of describing the research and development and
related issues."
-- http://plg.uwaterloo.ca/~gvcormac/treccorpus/
(MIT 라이센스)
저작권 (C) 2009-2016 Mikel Lindsaar
이에 따라이 소프트웨어 및 관련 문서 파일 ( '소프트웨어')의 사본을 얻는 사람에게 허가는 제한없이 소프트웨어를 처리 할 수있는 권한이 부여됩니다. , 소프트웨어의 사본을 게시, 배포, 서브 리센스 및/또는 판매하고, 소프트웨어가 제공하도록하는 사람을 다음과 같은 조건에 따라 할 수 있도록합니다.
위의 저작권 통지 및이 권한 통지는 소프트웨어의 모든 사본 또는 실질적인 부분에 포함되어야합니다.
이 소프트웨어는 상업성, 특정 목적에 대한 적합성 및 비 침해에 대한 보증을 포함하여 명시 적 또는 묵시적 보증 없이도 '있는 그대로'제공됩니다. 어떠한 경우에도 저자 또는 저작권 보유자는 계약, 불법 행위 또는 기타, 소프트웨어 또는 사용 또는 기타 거래와 관련하여 계약, 불법 행위 또는 기타의 행동에 관계없이 청구, 손해 또는 기타 책임에 대해 책임을지지 않아야합니다. 소프트웨어.