1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
|
# encoding: utf-8
# frozen_string_literal: true
require "yaml"
module Mail
# The Message class provides a single point of access to all things to do with an
# email message.
#
# You create a new email message by calling the Mail::Message.new method, or just
# Mail.new
#
# A Message object by default has the following objects inside it:
#
# * A Header object which contains all information and settings of the header of the email
# * Body object which contains all parts of the email that are not part of the header, this
# includes any attachments, body text, MIME parts etc.
#
# ==Per RFC2822
#
# 2.1. General Description
#
# At the most basic level, a message is a series of characters. A
# message that is conformant with this standard is comprised of
# characters with values in the range 1 through 127 and interpreted as
# US-ASCII characters [ASCII]. For brevity, this document sometimes
# refers to this range of characters as simply "US-ASCII characters".
#
# Note: This standard specifies that messages are made up of characters
# in the US-ASCII range of 1 through 127. There are other documents,
# specifically the MIME document series [RFC2045, RFC2046, RFC2047,
# RFC2048, RFC2049], that extend this standard to allow for values
# outside of that range. Discussion of those mechanisms is not within
# the scope of this standard.
#
# Messages are divided into lines of characters. A line is a series of
# characters that is delimited with the two characters carriage-return
# and line-feed; that is, the carriage return (CR) character (ASCII
# value 13) followed immediately by the line feed (LF) character (ASCII
# value 10). (The carriage-return/line-feed pair is usually written in
# this document as "CRLF".)
#
# A message consists of header fields (collectively called "the header
# of the message") followed, optionally, by a body. The header is a
# sequence of lines of characters with special syntax as defined in
# this standard. The body is simply a sequence of characters that
# follows the header and is separated from the header by an empty line
# (i.e., a line with nothing preceding the CRLF).
class Message
include Constants
include Utilities
# ==Making an email
#
# You can make an new mail object via a block, passing a string, file or direct assignment.
#
# ===Making an email via a block
#
# mail = Mail.new do
# from 'mikel@test.lindsaar.net'
# to 'you@test.lindsaar.net'
# subject 'This is a test email'
# body File.read('body.txt')
# end
#
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
#
# ===Making an email via passing a string
#
# mail = Mail.new("To: mikel@test.lindsaar.net\r\nSubject: Hello\r\n\r\nHi there!")
# mail.body.to_s #=> 'Hi there!'
# mail.subject #=> 'Hello'
# mail.to #=> 'mikel@test.lindsaar.net'
#
# ===Making an email from a file
#
# mail = Mail.read('path/to/file.eml')
# mail.body.to_s #=> 'Hi there!'
# mail.subject #=> 'Hello'
# mail.to #=> 'mikel@test.lindsaar.net'
#
# ===Making an email via assignment
#
# You can assign values to a mail object via four approaches:
#
# * Message#field_name=(value)
# * Message#field_name(value)
# * Message#['field_name']=(value)
# * Message#[:field_name]=(value)
#
# Examples:
#
# mail = Mail.new
# mail['from'] = 'mikel@test.lindsaar.net'
# mail[:to] = 'you@test.lindsaar.net'
# mail.subject 'This is a test email'
# mail.body = 'This is a body'
#
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
#
def initialize(*args, &block)
@body = nil
@body_raw = nil
@separate_parts = false
@text_part = nil
@html_part = nil
@errors = nil
@header = nil
@charset = self.class.default_charset
@defaulted_charset = true
@smtp_envelope_from = nil
@smtp_envelope_to = nil
@perform_deliveries = true
@raise_delivery_errors = true
@delivery_handler = nil
@delivery_method = Mail.delivery_method.dup
@transport_encoding = Mail::Encodings.get_encoding('7bit')
@mark_for_delete = false
if args.flatten.first.respond_to?(:each_pair)
init_with_hash(args.flatten.first)
else
init_with_string(args.flatten[0].to_s)
end
if block_given?
instance_eval(&block)
end
self
end
# If you assign a delivery handler, mail will call :deliver_mail on the
# object you assign to delivery_handler, it will pass itself as the
# single argument.
#
# If you define a delivery_handler, then you are responsible for the
# following actions in the delivery cycle:
#
# * Appending the mail object to Mail.deliveries as you see fit.
# * Checking the mail.perform_deliveries flag to decide if you should
# actually call :deliver! the mail object or not.
# * Checking the mail.raise_delivery_errors flag to decide if you
# should raise delivery errors if they occur.
# * Actually calling :deliver! (with the bang) on the mail object to
# get it to deliver itself.
#
# A simplest implementation of a delivery_handler would be
#
# class MyObject
#
# def initialize
# @mail = Mail.new('To: mikel@test.lindsaar.net')
# @mail.delivery_handler = self
# end
#
# attr_accessor :mail
#
# def deliver_mail(mail)
# yield
# end
# end
#
# Then doing:
#
# obj = MyObject.new
# obj.mail.deliver
#
# Would cause Mail to call obj.deliver_mail passing itself as a parameter,
# which then can just yield and let Mail do its own private do_delivery
# method.
attr_accessor :delivery_handler
# If set to false, mail will go through the motions of doing a delivery,
# but not actually call the delivery method or append the mail object to
# the Mail.deliveries collection. Useful for testing.
#
# Mail.deliveries.size #=> 0
# mail.delivery_method :smtp
# mail.perform_deliveries = false
# mail.deliver # Mail::SMTP not called here
# Mail.deliveries.size #=> 0
#
# If you want to test and query the Mail.deliveries collection to see what
# mail you sent, you should set perform_deliveries to true and use
# the :test mail delivery_method:
#
# Mail.deliveries.size #=> 0
# mail.delivery_method :test
# mail.perform_deliveries = true
# mail.deliver
# Mail.deliveries.size #=> 1
#
# This setting is ignored by mail (though still available as a flag) if you
# define a delivery_handler
attr_accessor :perform_deliveries
# If set to false, mail will silently catch and ignore any exceptions
# raised through attempting to deliver an email.
#
# This setting is ignored by mail (though still available as a flag) if you
# define a delivery_handler
attr_accessor :raise_delivery_errors
def self.default_charset; @@default_charset; end
def self.default_charset=(charset); @@default_charset = charset; end
self.default_charset = 'UTF-8'
def register_for_delivery_notification(observer)
STDERR.puts("Message#register_for_delivery_notification is deprecated, please call Mail.register_observer instead")
Mail.register_observer(observer)
end
def inform_observers
Mail.inform_observers(self)
end
def inform_interceptors
Mail.inform_interceptors(self)
end
# Delivers an mail object.
#
# Examples:
#
# mail = Mail.read('file.eml')
# mail.deliver
def deliver
inform_interceptors
if delivery_handler
delivery_handler.deliver_mail(self) { do_delivery }
else
do_delivery
end
inform_observers
self
end
# This method bypasses checking perform_deliveries and raise_delivery_errors,
# so use with caution.
#
# It still however fires off the interceptors and calls the observers callbacks if they are defined.
#
# Returns self
def deliver!
inform_interceptors
response = delivery_method.deliver!(self)
inform_observers
delivery_method.settings[:return_response] ? response : self
end
def delivery_method(method = nil, settings = {})
unless method
@delivery_method
else
@delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
end
end
def reply(*args, &block)
self.class.new.tap do |reply|
if message_id
bracketed_message_id = "<#{message_id}>"
reply.in_reply_to = bracketed_message_id
if !references.nil?
refs = [references].flatten.map { |r| "<#{r}>" }
refs << bracketed_message_id
reply.references = refs.join(' ')
elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
end
reply.references ||= bracketed_message_id
end
if subject
reply.subject = subject =~ /^Re:/i ? subject : "RE: #{subject}"
end
if reply_to || from
reply.to = self[reply_to ? :reply_to : :from].to_s
end
if to
reply.from = self[:to].formatted.first.to_s
end
unless args.empty?
if args.flatten.first.respond_to?(:each_pair)
reply.send(:init_with_hash, args.flatten.first)
else
reply.send(:init_with_string, args.flatten[0].to_s.strip)
end
end
if block_given?
reply.instance_eval(&block)
end
end
end
# Provides the operator needed for sort et al.
#
# Compares this mail object with another mail object, this is done by date, so an
# email that is older than another will appear first.
#
# Example:
#
# mail1 = Mail.new do
# date(Time.now)
# end
# mail2 = Mail.new do
# date(Time.now - 86400) # 1 day older
# end
# [mail2, mail1].sort #=> [mail2, mail1]
def <=>(other)
if other.nil?
1
else
self.date <=> other.date
end
end
# Two emails are the same if they have the same fields and body contents. One
# gotcha here is that Mail will insert Message-IDs when calling encoded, so doing
# mail1.encoded == mail2.encoded is most probably not going to return what you think
# as the assigned Message-IDs by Mail (if not already defined as the same) will ensure
# that the two objects are unique, and this comparison will ALWAYS return false.
#
# So the == operator has been defined like so: Two messages are the same if they have
# the same content, ignoring the Message-ID field, unless BOTH emails have a defined and
# different Message-ID value, then they are false.
#
# So, in practice the == operator works like this:
#
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
# m1 == m2 #=> true
#
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
# m1 == m2 #=> true
#
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
# m1 == m2 #=> true
#
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
# m1 == m2 #=> true
#
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
# m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
# m1 == m2 #=> false
def ==(other)
return false unless other.respond_to?(:encoded)
if self.message_id && other.message_id
self.encoded == other.encoded
else
self_message_id, other_message_id = self.message_id, other.message_id
begin
self.message_id, other.message_id = '<temp@test>', '<temp@test>'
self.encoded == other.encoded
ensure
self.message_id, other.message_id = self_message_id, other_message_id
end
end
end
def initialize_copy(original)
super
@header = @header.dup
end
# Provides access to the raw source of the message as it was when it
# was instantiated. This is set at initialization and so is untouched
# by the parsers or decoder / encoders
#
# Example:
#
# mail = Mail.new('This is an invalid email message')
# mail.raw_source #=> "This is an invalid email message"
def raw_source
@raw_source
end
# Sets the envelope from for the email
def set_envelope( val )
@raw_envelope = val
@envelope = Mail::Envelope.new( val )
end
# The raw_envelope is the From mikel@test.lindsaar.net Mon May 2 16:07:05 2009
# type field that you can see at the top of any email that has come
# from a mailbox
def raw_envelope
@raw_envelope
end
def envelope_from
@envelope ? @envelope.from : nil
end
def envelope_date
@envelope ? @envelope.date : nil
end
# Sets the header of the message object.
#
# Example:
#
# mail.header = 'To: mikel@test.lindsaar.net\r\nFrom: Bob@bob.com'
# mail.header #=> <#Mail::Header
def header=(value)
@header = Mail::Header.new(value, charset)
end
# Returns the header object of the message object. Or, if passed
# a parameter sets the value.
#
# Example:
#
# mail = Mail::Message.new('To: mikel\r\nFrom: you')
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
#
# mail.header #=> nil
# mail.header 'To: mikel\r\nFrom: you'
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
def header(value = nil)
value ? self.header = value : @header
end
# Provides a way to set custom headers, by passing in a hash
def headers(hash = {})
hash.each_pair do |k,v|
header[k] = v
end
end
# Returns a list of parser errors on the header, each field that had an error
# will be reparsed as an unstructured field to preserve the data inside, but
# will not be used for further processing.
#
# It returns a nested array of [field_name, value, original_error_message]
# per error found.
#
# Example:
#
# message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
# message.errors.size #=> 1
# message.errors.first[0] #=> "Content-Transfer-Encoding"
# message.errors.first[1] #=> "weirdo"
# message.errors.first[3] #=> <The original error message exception>
#
# This is a good first defence on detecting spam by the way. Some spammers send
# invalid emails to try and get email parsers to give up parsing them.
def errors
header.errors
end
# Returns the Bcc value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
# mail.bcc #=> ['mikel@test.lindsaar.net']
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
# mail.bcc #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
# mail.bcc << 'ada@test.lindsaar.net'
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def bcc( val = nil )
default :bcc, val
end
# Sets the Bcc value of the mail object, pass in a string of the field
#
# Example:
#
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
# mail.bcc #=> ['mikel@test.lindsaar.net']
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def bcc=( val )
header[:bcc] = val
end
# Returns the Cc value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
# mail.cc #=> ['mikel@test.lindsaar.net']
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
# mail.cc #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
# mail.cc << 'ada@test.lindsaar.net'
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def cc( val = nil )
default :cc, val
end
# Sets the Cc value of the mail object, pass in a string of the field
#
# Example:
#
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
# mail.cc #=> ['mikel@test.lindsaar.net']
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def cc=( val )
header[:cc] = val
end
def comments( val = nil )
default :comments, val
end
def comments=( val )
header[:comments] = val
end
def content_description( val = nil )
default :content_description, val
end
def content_description=( val )
header[:content_description] = val
end
def content_disposition( val = nil )
default :content_disposition, val
end
def content_disposition=( val )
header[:content_disposition] = val
end
def content_id( val = nil )
default :content_id, val
end
def content_id=( val )
header[:content_id] = val
end
def content_location( val = nil )
default :content_location, val
end
def content_location=( val )
header[:content_location] = val
end
def content_transfer_encoding( val = nil )
default :content_transfer_encoding, val
end
def content_transfer_encoding=( val )
header[:content_transfer_encoding] = val
end
def content_type( val = nil )
default :content_type, val
end
def content_type=( val )
header[:content_type] = val
end
def date( val = nil )
default :date, val
end
def date=( val )
header[:date] = val
end
def transport_encoding( val = nil)
if val
self.transport_encoding = val
else
@transport_encoding
end
end
def transport_encoding=( val )
@transport_encoding = Mail::Encodings.get_encoding(val)
end
# Returns the From value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
# mail.from #=> ['mikel@test.lindsaar.net']
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.from 'Mikel <mikel@test.lindsaar.net>'
# mail.from #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.from 'Mikel <mikel@test.lindsaar.net>'
# mail.from << 'ada@test.lindsaar.net'
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def from( val = nil )
default :from, val
end
# Sets the From value of the mail object, pass in a string of the field
#
# Example:
#
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
# mail.from #=> ['mikel@test.lindsaar.net']
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def from=( val )
header[:from] = val
end
def in_reply_to( val = nil )
default :in_reply_to, val
end
def in_reply_to=( val )
header[:in_reply_to] = val
end
def keywords( val = nil )
default :keywords, val
end
def keywords=( val )
header[:keywords] = val
end
# Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID
# consists of what is INSIDE the < > usually seen in the mail header, so this method
# will return only what is inside.
#
# Example:
#
# mail.message_id = '<1234@message.id>'
# mail.message_id #=> '1234@message.id'
#
# Also allows you to set the Message-ID by passing a string as a parameter
#
# mail.message_id '<1234@message.id>'
# mail.message_id #=> '1234@message.id'
def message_id( val = nil )
default :message_id, val
end
# Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE
# the < > usually seen in the mail header, so this method will return only what is inside.
#
# mail.message_id = '<1234@message.id>'
# mail.message_id #=> '1234@message.id'
def message_id=( val )
header[:message_id] = val
end
# Returns the MIME version of the email as a string
#
# Example:
#
# mail.mime_version = '1.0'
# mail.mime_version #=> '1.0'
#
# Also allows you to set the MIME version by passing a string as a parameter.
#
# Example:
#
# mail.mime_version '1.0'
# mail.mime_version #=> '1.0'
def mime_version( val = nil )
default :mime_version, val
end
# Sets the MIME version of the email by accepting a string
#
# Example:
#
# mail.mime_version = '1.0'
# mail.mime_version #=> '1.0'
def mime_version=( val )
header[:mime_version] = val
end
def received( val = nil )
if val
header[:received] = val
else
header[:received]
end
end
def received=( val )
header[:received] = val
end
def references( val = nil )
default :references, val
end
def references=( val )
header[:references] = val
end
# Returns the Reply-To value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.reply_to #=> ['mikel@test.lindsaar.net']
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
# mail.reply_to #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
# mail.reply_to << 'ada@test.lindsaar.net'
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def reply_to( val = nil )
default :reply_to, val
end
# Sets the Reply-To value of the mail object, pass in a string of the field
#
# Example:
#
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.reply_to #=> ['mikel@test.lindsaar.net']
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def reply_to=( val )
header[:reply_to] = val
end
# Returns the Resent-Bcc value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_bcc << 'ada@test.lindsaar.net'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_bcc( val = nil )
default :resent_bcc, val
end
# Sets the Resent-Bcc value of the mail object, pass in a string of the field
#
# Example:
#
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_bcc=( val )
header[:resent_bcc] = val
end
# Returns the Resent-Cc value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_cc << 'ada@test.lindsaar.net'
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_cc( val = nil )
default :resent_cc, val
end
# Sets the Resent-Cc value of the mail object, pass in a string of the field
#
# Example:
#
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_cc=( val )
header[:resent_cc] = val
end
def resent_date( val = nil )
default :resent_date, val
end
def resent_date=( val )
header[:resent_date] = val
end
# Returns the Resent-From value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_from #=> ['mikel@test.lindsaar.net']
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.resent_from ['Mikel <mikel@test.lindsaar.net>']
# mail.resent_from #=> 'mikel@test.lindsaar.net'
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.resent_from 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_from << 'ada@test.lindsaar.net'
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_from( val = nil )
default :resent_from, val
end
# Sets the Resent-From value of the mail object, pass in a string of the field
#
# Example:
#
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_from #=> ['mikel@test.lindsaar.net']
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_from=( val )
header[:resent_from] = val
end
def resent_message_id( val = nil )
default :resent_message_id, val
end
def resent_message_id=( val )
header[:resent_message_id] = val
end
# Returns the Resent-Sender value of the mail object, as a single string of an address
# spec. A sender per RFC 2822 must be a single address, so you can not append to
# this address.
#
# Example:
#
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.resent_sender 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
def resent_sender( val = nil )
default :resent_sender, val
end
# Sets the Resent-Sender value of the mail object, pass in a string of the field
#
# Example:
#
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
def resent_sender=( val )
header[:resent_sender] = val
end
# Returns the Resent-To value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_to #=> ['mikel@test.lindsaar.net']
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_to #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_to << 'ada@test.lindsaar.net'
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_to( val = nil )
default :resent_to, val
end
# Sets the Resent-To value of the mail object, pass in a string of the field
#
# Example:
#
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.resent_to #=> ['mikel@test.lindsaar.net']
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def resent_to=( val )
header[:resent_to] = val
end
# Returns the return path of the mail object, or sets it if you pass a string
def return_path( val = nil )
default :return_path, val
end
# Sets the return path of the object
def return_path=( val )
header[:return_path] = val
end
# Returns the Sender value of the mail object, as a single string of an address
# spec. A sender per RFC 2822 must be a single address.
#
# Example:
#
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
# mail.sender #=> 'mikel@test.lindsaar.net'
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.sender 'Mikel <mikel@test.lindsaar.net>'
# mail.sender #=> 'mikel@test.lindsaar.net'
def sender( val = nil )
default :sender, val
end
# Sets the Sender value of the mail object, pass in a string of the field
#
# Example:
#
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
# mail.sender #=> 'mikel@test.lindsaar.net'
def sender=( val )
header[:sender] = val
end
# Returns the SMTP Envelope From value of the mail object, as a single
# string of an address spec.
#
# Defaults to Return-Path, Sender, or the first From address.
#
# Example:
#
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.smtp_envelope_from 'Mikel <mikel@test.lindsaar.net>'
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
def smtp_envelope_from( val = nil )
if val
self.smtp_envelope_from = val
else
@smtp_envelope_from || return_path || sender || from_addrs.first
end
end
# Sets the From address on the SMTP Envelope.
#
# Example:
#
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
def smtp_envelope_from=( val )
@smtp_envelope_from = val
end
# Returns the SMTP Envelope To value of the mail object.
#
# Defaults to #destinations: To, Cc, and Bcc addresses.
#
# Example:
#
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.smtp_envelope_to ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
def smtp_envelope_to( val = nil )
if val
self.smtp_envelope_to = val
else
@smtp_envelope_to || destinations
end
end
# Sets the To addresses on the SMTP Envelope.
#
# Example:
#
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
#
# mail.smtp_envelope_to = ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
def smtp_envelope_to=( val )
@smtp_envelope_to =
case val
when Array, NilClass
val
else
[val]
end
end
# Returns the decoded value of the subject field, as a single string.
#
# Example:
#
# mail.subject = "G'Day mate"
# mail.subject #=> "G'Day mate"
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
# mail.subject #=> "This is あ string"
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.subject "G'Day mate"
# mail.subject #=> "G'Day mate"
def subject( val = nil )
default :subject, val
end
# Sets the Subject value of the mail object, pass in a string of the field
#
# Example:
#
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
# mail.subject #=> "This is あ string"
def subject=( val )
header[:subject] = val
end
# Returns the To value of the mail object as an array of strings of
# address specs.
#
# Example:
#
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
# mail.to #=> ['mikel@test.lindsaar.net']
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
#
# Also allows you to set the value by passing a value as a parameter
#
# Example:
#
# mail.to 'Mikel <mikel@test.lindsaar.net>'
# mail.to #=> ['mikel@test.lindsaar.net']
#
# Additionally, you can append new addresses to the returned Array like
# object.
#
# Example:
#
# mail.to 'Mikel <mikel@test.lindsaar.net>'
# mail.to << 'ada@test.lindsaar.net'
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def to( val = nil )
default :to, val
end
# Sets the To value of the mail object, pass in a string of the field
#
# Example:
#
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
# mail.to #=> ['mikel@test.lindsaar.net']
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
def to=( val )
header[:to] = val
end
# Returns the default value of the field requested as a symbol.
#
# Each header field has a :default method which returns the most common use case for
# that field, for example, the date field types will return a DateTime object when
# sent :default, the subject, or unstructured fields will return a decoded string of
# their value, the address field types will return a single addr_spec or an array of
# addr_specs if there is more than one.
def default( sym, val = nil )
if val
header[sym] = val
else
header[sym].default if header[sym]
end
end
# Sets the body object of the message object.
#
# Example:
#
# mail.body = 'This is the body'
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
#
# You can also reset the body of an Message object by setting body to nil
#
# Example:
#
# mail.body = 'this is the body'
# mail.body.encoded #=> 'this is the body'
# mail.body = nil
# mail.body.encoded #=> ''
#
# If you try and set the body of an email that is a multipart email, then instead
# of deleting all the parts of your email, mail will add a text/plain part to
# your email:
#
# mail.add_file 'somefilename.png'
# mail.parts.length #=> 1
# mail.body = "This is a body"
# mail.parts.length #=> 2
# mail.parts.last.content_type.content_type #=> 'This is a body'
def body=(value)
body_lazy(value)
end
# Returns the body of the message object. Or, if passed
# a parameter sets the value.
#
# Example:
#
# mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
#
# mail.body 'This is another body'
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...
def body(value = nil)
if value
self.body = value
# add_encoding_to_body
else
process_body_raw if @body_raw
@body
end
end
def body_encoding(value)
if value.nil?
body.encoding
else
body.encoding = value
end
end
def body_encoding=(value)
body.encoding = value
end
# Returns the list of addresses this message should be sent to by
# collecting the addresses off the to, cc and bcc fields.
#
# Example:
#
# mail.to = 'mikel@test.lindsaar.net'
# mail.cc = 'sam@test.lindsaar.net'
# mail.bcc = 'bob@test.lindsaar.net'
# mail.destinations.length #=> 3
# mail.destinations.first #=> 'mikel@test.lindsaar.net'
def destinations
[to_addrs, cc_addrs, bcc_addrs].compact.flatten
end
# Returns an array of addresses (the encoded value) in the From field,
# if no From field, returns an empty array
def from_addrs
from ? [from].flatten : []
end
# Returns an array of addresses (the encoded value) in the To field,
# if no To field, returns an empty array
def to_addrs
to ? [to].flatten : []
end
# Returns an array of addresses (the encoded value) in the Cc field,
# if no Cc field, returns an empty array
def cc_addrs
cc ? [cc].flatten : []
end
# Returns an array of addresses (the encoded value) in the Bcc field,
# if no Bcc field, returns an empty array
def bcc_addrs
bcc ? [bcc].flatten : []
end
# Allows you to add an arbitrary header
#
# Example:
#
# mail['foo'] = '1234'
# mail['foo'].to_s #=> '1234'
def []=(name, value)
if name.to_s == 'body'
self.body = value
elsif name.to_s =~ /content[-_]type/i
header[name] = value
elsif name.to_s == 'charset'
self.charset = value
else
header[name] = value
end
end
# Allows you to read an arbitrary header
#
# Example:
#
# mail['foo'] = '1234'
# mail['foo'].to_s #=> '1234'
def [](name)
header[underscoreize(name)]
end
# Method Missing in this implementation allows you to set any of the
# standard fields directly as you would the "to", "subject" etc.
#
# Those fields used most often (to, subject et al) are given their
# own method for ease of documentation and also to avoid the hook
# call to method missing.
#
# This will only catch the known fields listed in:
#
# Mail::Field::KNOWN_FIELDS
#
# as per RFC 2822, any ruby string or method name could pretty much
# be a field name, so we don't want to just catch ANYTHING sent to
# a message object and interpret it as a header.
#
# This method provides all three types of header call to set, read
# and explicitly set with the = operator
#
# Examples:
#
# mail.comments = 'These are some comments'
# mail.comments #=> 'These are some comments'
#
# mail.comments 'These are other comments'
# mail.comments #=> 'These are other comments'
#
#
# mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
#
# mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
#
#
# mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
# mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
#
# mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
# mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'
def method_missing(name, *args, &block)
#:nodoc:
# Only take the structured fields, as we could take _anything_ really
# as it could become an optional field... "but therin lies the dark side"
field_name = underscoreize(name).chomp("=")
if Mail::Field::KNOWN_FIELDS.include?(field_name)
if args.empty?
header[field_name]
else
header[field_name] = args.first
end
else
super # otherwise pass it on
end
#:startdoc:
end
# Returns an FieldList of all the fields in the header in the order that
# they appear in the header
def header_fields
header.fields
end
# Returns true if the message has a message ID field, the field may or may
# not have a value, but the field exists or not.
def has_message_id?
header.has_message_id?
end
# Returns true if the message has a Date field, the field may or may
# not have a value, but the field exists or not.
def has_date?
header.has_date?
end
# Returns true if the message has a Mime-Version field, the field may or may
# not have a value, but the field exists or not.
def has_mime_version?
header.has_mime_version?
end
def has_content_type?
tmp = header[:content_type].main_type rescue nil
!!tmp
end
def has_charset?
tmp = header[:content_type].parameters rescue nil
!!(has_content_type? && tmp && tmp['charset'])
end
def has_content_transfer_encoding?
header[:content_transfer_encoding] && Utilities.blank?(header[:content_transfer_encoding].errors)
end
def has_transfer_encoding? # :nodoc:
STDERR.puts(":has_transfer_encoding? is deprecated in Mail 1.4.3. Please use has_content_transfer_encoding?\n#{caller}")
has_content_transfer_encoding?
end
# Creates a new empty Message-ID field and inserts it in the correct order
# into the Header. The MessageIdField object will automatically generate
# a unique message ID if you try and encode it or output it to_s without
# specifying a message id.
#
# It will preserve the message ID you specify if you do.
def add_message_id(msg_id_val = '')
header['message-id'] = msg_id_val
end
# Creates a new empty Date field and inserts it in the correct order
# into the Header. The DateField object will automatically generate
# DateTime.now's date if you try and encode it or output it to_s without
# specifying a date yourself.
#
# It will preserve any date you specify if you do.
def add_date(date_val = '')
header['date'] = date_val
end
# Creates a new empty Mime Version field and inserts it in the correct order
# into the Header. The MimeVersion object will automatically generate
# set itself to '1.0' if you try and encode it or output it to_s without
# specifying a version yourself.
#
# It will preserve any date you specify if you do.
def add_mime_version(ver_val = '')
header['mime-version'] = ver_val
end
# Adds a content type and charset if the body is US-ASCII
#
# Otherwise raises a warning
def add_content_type
header[:content_type] = 'text/plain'
end
# Adds a content type and charset if the body is US-ASCII
#
# Otherwise raises a warning
def add_charset
if !body.empty?
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
# has not specified an encoding explicitly.
if @defaulted_charset && body.raw_source.not_ascii_only? && !self.attachment?
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
STDERR.puts(warning)
end
header[:content_type].parameters['charset'] = @charset
end
end
# Adds a content transfer encoding
#
# Otherwise raises a warning
def add_content_transfer_encoding
if body.only_us_ascii?
header[:content_transfer_encoding] = '7bit'
else
warning = "Non US-ASCII detected and no content-transfer-encoding defined.\nDefaulting to 8bit, set your own if this is incorrect.\n"
STDERR.puts(warning)
header[:content_transfer_encoding] = '8bit'
end
end
def add_transfer_encoding # :nodoc:
STDERR.puts(":add_transfer_encoding is deprecated in Mail 1.4.3. Please use add_content_transfer_encoding\n#{caller}")
add_content_transfer_encoding
end
def transfer_encoding # :nodoc:
STDERR.puts(":transfer_encoding is deprecated in Mail 1.4.3. Please use content_transfer_encoding\n#{caller}")
content_transfer_encoding
end
# Returns the MIME media type of part we are on, this is taken from the content-type header
def mime_type
has_content_type? ? header[:content_type].string : nil rescue nil
end
def message_content_type
STDERR.puts(":message_content_type is deprecated in Mail 1.4.3. Please use mime_type\n#{caller}")
mime_type
end
# Returns the character set defined in the content type field
def charset
if @header
has_content_type? ? content_type_parameters['charset'] : @charset
else
@charset
end
end
# Sets the charset to the supplied value.
def charset=(value)
@defaulted_charset = false
@charset = value
@header.charset = value
end
# Returns the main content type
def main_type
has_content_type? ? header[:content_type].main_type : nil rescue nil
end
# Returns the sub content type
def sub_type
has_content_type? ? header[:content_type].sub_type : nil rescue nil
end
# Returns the content type parameters
def mime_parameters
STDERR.puts(':mime_parameters is deprecated in Mail 1.4.3, please use :content_type_parameters instead')
content_type_parameters
end
# Returns the content type parameters
def content_type_parameters
has_content_type? ? header[:content_type].parameters : nil rescue nil
end
# Returns true if the message is multipart
def multipart?
has_content_type? ? !!(main_type =~ /^multipart$/i) : false
end
# Returns true if the message is a multipart/report
def multipart_report?
multipart? && sub_type =~ /^report$/i
end
# Returns true if the message is a multipart/report; report-type=delivery-status;
def delivery_status_report?
multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i
end
# returns the part in a multipart/report email that has the content-type delivery-status
def delivery_status_part
@delivery_stats_part ||= parts.select { |p| p.delivery_status_report_part? }.first
end
def bounced?
delivery_status_part and delivery_status_part.bounced?
end
def action
delivery_status_part and delivery_status_part.action
end
def final_recipient
delivery_status_part and delivery_status_part.final_recipient
end
def error_status
delivery_status_part and delivery_status_part.error_status
end
def diagnostic_code
delivery_status_part and delivery_status_part.diagnostic_code
end
def remote_mta
delivery_status_part and delivery_status_part.remote_mta
end
def retryable?
delivery_status_part and delivery_status_part.retryable?
end
# Returns the current boundary for this message part
def boundary
content_type_parameters ? content_type_parameters['boundary'] : nil
end
# Returns a parts list object of all the parts in the message
def parts
body.parts
end
# Returns an AttachmentsList object, which holds all of the attachments in
# the receiver object (either the entire email or a part within) and all
# of its descendants.
#
# It also allows you to add attachments to the mail object directly, like so:
#
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
#
# If you do this, then Mail will take the file name and work out the MIME media type
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
# base64 encode the contents of the attachment all for you.
#
# You can also specify overrides if you want by passing a hash instead of a string:
#
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :content => File.read('/path/to/filename.jpg')}
#
# If you want to use a different encoding than Base64, you can pass an encoding in,
# but then it is up to you to pass in the content pre-encoded, and don't expect
# Mail to know how to decode this data:
#
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :encoding => 'SpecialEncoding',
# :content => file_content }
#
# You can also search for specific attachments:
#
# # By Filename
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
#
# # or by index
# mail.attachments[0] #=> Mail::Part (first attachment)
#
def attachments
parts.attachments
end
def has_attachments?
!attachments.empty?
end
# Accessor for html_part
def html_part(&block)
if block_given?
self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
else
@html_part || find_first_mime_type('text/html')
end
end
# Accessor for text_part
def text_part(&block)
if block_given?
self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
else
@text_part || find_first_mime_type('text/plain')
end
end
# Helper to add a html part to a multipart/alternative email. If this and
# text_part are both defined in a message, then it will be a multipart/alternative
# message and set itself that way.
def html_part=(msg)
# Assign the html part and set multipart/alternative if there's a text part.
if msg
msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)
@html_part = msg
@html_part.content_type = 'text/html' unless @html_part.has_content_type?
add_multipart_alternate_header if text_part
add_part @html_part
# If nil, delete the html part and back out of multipart/alternative.
elsif @html_part
parts.delete_if { |p| p.object_id == @html_part.object_id }
@html_part = nil
if text_part
self.content_type = nil
body.boundary = nil
end
end
end
# Helper to add a text part to a multipart/alternative email. If this and
# html_part are both defined in a message, then it will be a multipart/alternative
# message and set itself that way.
def text_part=(msg)
# Assign the text part and set multipart/alternative if there's an html part.
if msg
msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)
@text_part = msg
@text_part.content_type = 'text/plain' unless @text_part.has_content_type?
add_multipart_alternate_header if html_part
add_part @text_part
# If nil, delete the text part and back out of multipart/alternative.
elsif @text_part
parts.delete_if { |p| p.object_id == @text_part.object_id }
@text_part = nil
if html_part
self.content_type = nil
body.boundary = nil
end
end
end
# Adds a part to the parts list or creates the part list
def add_part(part)
if !body.multipart? && !Utilities.blank?(self.body.decoded)
@text_part = Mail::Part.new('Content-Type: text/plain;')
@text_part.body = body.decoded
self.body << @text_part
add_multipart_alternate_header
end
add_boundary
self.body << part
end
# Allows you to add a part in block form to an existing mail message object
#
# Example:
#
# mail = Mail.new do
# part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
# p.part :content_type => "text/plain", :body => "test text\nline #2"
# p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
# end
# end
def part(params = {})
new_part = Part.new(params)
yield new_part if block_given?
add_part(new_part)
end
# Adds a file to the message. You have two options with this method, you can
# just pass in the absolute path to the file you want and Mail will read the file,
# get the filename from the path you pass in and guess the MIME media type, or you
# can pass in the filename as a string, and pass in the file content as a blob.
#
# Example:
#
# m = Mail.new
# m.add_file('/path/to/filename.png')
#
# m = Mail.new
# m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
#
# Note also that if you add a file to an existing message, Mail will convert that message
# to a MIME multipart email, moving whatever plain text body you had into its own text
# plain part.
#
# Example:
#
# m = Mail.new do
# body 'this is some text'
# end
# m.multipart? #=> false
# m.add_file('/path/to/filename.png')
# m.multipart? #=> true
# m.parts.first.content_type.content_type #=> 'text/plain'
# m.parts.last.content_type.content_type #=> 'image/png'
#
# See also #attachments
def add_file(values)
convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
add_multipart_mixed_header
if values.is_a?(String)
basename = File.basename(values)
filedata = File.open(values, 'rb') { |f| f.read }
else
basename = values[:filename]
filedata = values
unless filedata[:content]
filedata = values.merge(:content=>File.open(values[:filename], 'rb') { |f| f.read })
end
end
self.attachments[basename] = filedata
end
def convert_to_multipart
text = body.decoded
self.body = ''
text_part = Mail::Part.new({:content_type => 'text/plain;',
:body => text})
text_part.charset = charset unless @defaulted_charset
self.body << text_part
end
# Encodes the message, calls encode on all its parts, gets an email message
# ready to send
def ready_to_send!
identify_and_set_transfer_encoding
parts.sort!([ "text/plain", "text/enriched", "text/html", "multipart/alternative" ])
parts.each do |part|
part.transport_encoding = transport_encoding
part.ready_to_send!
end
add_required_fields
end
def encode!
STDERR.puts("Deprecated in 1.1.0 in favour of :ready_to_send! as it is less confusing with encoding and decoding.")
ready_to_send!
end
# Outputs an encoded string representation of the mail message including
# all headers, attachments, etc. This is an encoded email in US-ASCII,
# so it is able to be directly sent to an email server.
def encoded
ready_to_send!
buffer = header.encoded
buffer << "\r\n"
buffer << body.encoded(content_transfer_encoding)
buffer
end
def without_attachments!
return self unless has_attachments?
parts.delete_if { |p| p.attachment? }
body_raw = if parts.empty?
''
else
body.encoded
end
@body = Mail::Body.new(body_raw)
self
end
def to_yaml(opts = {})
hash = {}
hash['headers'] = {}
header.fields.each do |field|
hash['headers'][field.name] = field.value
end
hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
hash['transport_encoding'] = transport_encoding.to_s
special_variables = [:@header, :@delivery_handler, :@transport_encoding]
if multipart?
hash['multipart_body'] = []
body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
special_variables.push(:@body, :@text_part, :@html_part)
end
(instance_variables.map(&:to_sym) - special_variables).each do |var|
hash[var.to_s] = instance_variable_get(var)
end
hash.to_yaml(opts)
end
def self.from_yaml(str)
hash = YAML.load(str)
m = self.new(:headers => hash['headers'])
hash.delete('headers')
hash.each do |k,v|
case
when k == 'delivery_handler'
begin
m.delivery_handler = Object.const_get(v) unless Utilities.blank?(v)
rescue NameError
end
when k == 'transport_encoding'
m.transport_encoding(v)
when k == 'multipart_body'
v.map {|part| m.add_part Mail::Part.from_yaml(part) }
when k =~ /^@/
m.instance_variable_set(k.to_sym, v)
end
end
m
end
def self.from_hash(hash)
Mail::Message.new(hash)
end
def to_s
encoded
end
def inspect
"#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
end
def decoded
case
when self.text?
decode_body_as_text
when self.attachment?
decode_body
when !self.multipart?
body.decoded
else
raise NoMethodError, 'Can not decode an entire message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
end
end
def read
if self.attachment?
decode_body
else
raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
end
end
def decode_body
body.decoded
end
# Returns true if this part is an attachment,
# false otherwise.
def attachment?
!!find_attachment
end
# Returns the attachment data if there is any
def attachment
@attachment
end
# Returns the filename of the attachment
def filename
find_attachment
end
def all_parts
parts.map { |p| [p, p.all_parts] }.flatten
end
def find_first_mime_type(mt)
all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
end
# Skips the deletion of this message. All other messages
# flagged for delete still will be deleted at session close (i.e. when
# #find exits). Only has an effect if you're using #find_and_delete
# or #find with :delete_after_find set to true.
def skip_deletion
@mark_for_delete = false
end
# Sets whether this message should be deleted at session close (i.e.
# after #find). Message will only be deleted if messages are retrieved
# using the #find_and_delete method, or by calling #find with
# :delete_after_find set to true.
def mark_for_delete=(value = true)
@mark_for_delete = value
end
# Returns whether message will be marked for deletion.
# If so, the message will be deleted at session close (i.e. after #find
# exits), but only if also using the #find_and_delete method, or by
# calling #find with :delete_after_find set to true.
#
# Side-note: Just to be clear, this method will return true even if
# the message hasn't yet been marked for delete on the mail server.
# However, if this method returns true, it *will be* marked on the
# server after each block yields back to #find or #find_and_delete.
def is_marked_for_delete?
return @mark_for_delete
end
def text?
has_content_type? ? !!(main_type =~ /^text$/i) : false
end
private
HEADER_SEPARATOR = /#{CRLF}#{CRLF}|#{CRLF}#{WSP}*#{CRLF}(?!#{WSP})/m
# 2.1. General Description
# A message consists of header fields (collectively called "the header
# of the message") followed, optionally, by a body. The header is a
# sequence of lines of characters with special syntax as defined in
# this standard. The body is simply a sequence of characters that
# follows the header and is separated from the header by an empty line
# (i.e., a line with nothing preceding the CRLF).
#
# Additionally, I allow for the case where someone might have put whitespace
# on the "gap line"
def parse_message
header_part, body_part = raw_source.lstrip.split(HEADER_SEPARATOR, 2)
self.header = header_part
self.body = body_part
end
def raw_source=(value)
value = value.dup.force_encoding(Encoding::BINARY) if RUBY_VERSION >= "1.9.1"
@raw_source = ::Mail::Utilities.to_crlf(value)
end
# see comments to body=. We take data and process it lazily
def body_lazy(value)
process_body_raw if @body_raw && value
case
when value == nil || value.length<=0
@body = Mail::Body.new('')
@body_raw = nil
add_encoding_to_body
when @body && @body.multipart?
@body << Mail::Part.new(value)
add_encoding_to_body
else
@body_raw = value
# process_body_raw
end
end
def process_body_raw
@body = Mail::Body.new(@body_raw)
@body_raw = nil
separate_parts if @separate_parts
add_encoding_to_body
end
def set_envelope_header
raw_string = raw_source.to_s
if match_data = raw_source.to_s.match(/\AFrom\s(#{TEXT}+)#{CRLF}/m)
set_envelope(match_data[1])
self.raw_source = raw_string.sub(match_data[0], "")
end
end
def separate_parts
body.split!(boundary)
end
def add_encoding_to_body
if has_content_transfer_encoding?
@body.encoding = content_transfer_encoding
end
end
def identify_and_set_transfer_encoding
if body && body.multipart?
self.content_transfer_encoding = @transport_encoding
else
self.content_transfer_encoding = body.get_best_encoding(@transport_encoding)
end
end
def add_required_fields
add_required_message_fields
add_multipart_mixed_header if body.multipart?
add_content_type unless has_content_type?
add_charset if text? && !has_charset?
add_content_transfer_encoding unless has_content_transfer_encoding?
end
def add_required_message_fields
add_date unless has_date?
add_mime_version unless has_mime_version?
add_message_id unless has_message_id?
end
def add_multipart_alternate_header
header['content-type'] = ContentTypeField.with_boundary('multipart/alternative').value
header['content_type'].parameters[:charset] = @charset
body.boundary = boundary
end
def add_boundary
unless body.boundary && boundary
header['content-type'] = 'multipart/mixed' unless header['content-type']
header['content-type'].parameters[:boundary] = ContentTypeField.generate_boundary
header['content_type'].parameters[:charset] = @charset
body.boundary = boundary
end
end
def add_multipart_mixed_header
unless header['content-type']
header['content-type'] = ContentTypeField.with_boundary('multipart/mixed').value
header['content_type'].parameters[:charset] = @charset
body.boundary = boundary
end
end
def init_with_hash(hash)
passed_in_options = IndifferentHash.new(hash)
self.raw_source = ''
@header = Mail::Header.new
@body = Mail::Body.new
@body_raw = nil
# We need to store the body until last, as we need all headers added first
body_content = nil
passed_in_options.each_pair do |k,v|
k = underscoreize(k).to_sym if k.class == String
if k == :headers
self.headers(v)
elsif k == :body
body_content = v
else
self[k] = v
end
end
if body_content
self.body = body_content
if has_content_transfer_encoding?
body.encoding = content_transfer_encoding
end
end
end
def init_with_string(string)
self.raw_source = string
set_envelope_header
parse_message
@separate_parts = multipart?
end
# Returns the filename of the attachment (if it exists) or returns nil
def find_attachment
content_type_name = header[:content_type].filename rescue nil
content_disp_name = header[:content_disposition].filename rescue nil
content_loc_name = header[:content_location].location rescue nil
case
when content_type && content_type_name
filename = content_type_name
when content_disposition && content_disp_name
filename = content_disp_name
when content_location && content_loc_name
filename = content_loc_name
else
filename = nil
end
filename = Mail::Encodings.decode_encode(filename, :decode) if filename rescue filename
filename
end
def do_delivery
begin
if perform_deliveries
delivery_method.deliver!(self)
end
rescue => e # Net::SMTP errors or sendmail pipe errors
raise e if raise_delivery_errors
end
end
def decode_body_as_text
Encodings.transcode_charset decode_body, charset, 'UTF-8'
end
end
end
|