GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — python-docs-ja/library/email.examples.po at 3.13 · python/python-docs-ja Expand file tree/ Copy pathemail.examples.poMore file actions 838 lines (818 loc) · 31 KB / Copy pathemail.examples.poFile metadata and controls838 lines (818 loc) · 31 KB 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 # SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # # Translators: # tomo, 2021 # 石井明久, 2024 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-05-16 14:19+0000\n" "PO-Revision-Date: 2021-06-28 01:05+0000\n" "Last-Translator: 石井明久, 2024\n" "Language-Team: Japanese (https://app.transifex.com/python-doc/teams/5390/" "ja/)\n" "Language: ja\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/email.examples.rst:4 msgid ":mod:`email`: Examples" msgstr ":mod:`email`: 使用例" #: ../../library/email.examples.rst:6 msgid "" "Here are a few examples of how to use the :mod:`email` package to read, " "write, and send simple email messages, as well as more complex MIME messages." msgstr "" "ここでは :mod:`email` パッケージを使って電子メールメッセージを読む・書く・送" "信するいくつかの例を紹介します。より複雑な MIME メッセージについても扱いま" "す。" #: ../../library/email.examples.rst:9 msgid "" "First, let's see how to create and send a simple text message (both the text " "content and the addresses may contain unicode characters):" msgstr "" "最初に、シンプルなテキストメッセージ (テキストコンテンツとアドレスの両方がユ" "ニコード文字を含み得る) を作成・送信する方法を見てみましょう:" msgid "" "# Import smtplib for the actual sending function\n" "import smtplib\n" "\n" "# Import the email modules we'll need\n" "from email.message import EmailMessage\n" "\n" "# Open the plain text file whose name is in textfile for reading.\n" "with open(textfile) as fp:\n" " # Create a text/plain message\n" " msg = EmailMessage()\n" " msg.set_content(fp.read())\n" "\n" "# me == the sender's email address\n" "# you == the recipient's email address\n" "msg['Subject'] = f'The contents of {textfile}'\n" "msg['From'] = me\n" "msg['To'] = you\n" "\n" "# Send the message via our own SMTP server.\n" "s = smtplib.SMTP('localhost')\n" "s.send_message(msg)\n" "s.quit()\n" msgstr "" "# 実際の送信に使う smtplib をインポートします\n" "import smtplib\n" "\n" "# 必要な email モジュールをインポートします\n" "from email.message import EmailMessage\n" "\n" "# textfile に名前が入っているプレーンテキストファイルを読み込み用に開きま" "す。\n" "with open(textfile) as fp:\n" " # text/plain メッセージを作成します\n" " msg = EmailMessage()\n" " msg.set_content(fp.read())\n" "\n" "# me == 送信者のメールアドレス\n" "# you == 受信者のメールアドレス\n" "msg['Subject'] = f'The contents of {textfile}'\n" "msg['From'] = me\n" "msg['To'] = you\n" "\n" "# 自分の SMTP サーバー経由でメッセージを送信します。\n" "s = smtplib.SMTP('localhost')\n" "s.send_message(msg)\n" "s.quit()\n" #: ../../library/email.examples.rst:15 msgid "" "Parsing :rfc:`822` headers can easily be done by the using the classes from " "the :mod:`~email.parser` module:" msgstr "" ":rfc:`822` ヘッダーの解析は、 :mod:`~email.parser` モジュールにあるクラスを使" "用することにより、簡単に実現できます:" msgid "" "# Import the email modules we'll need\n" "#from email.parser import BytesParser\n" "from email.parser import Parser\n" "from email.policy import default\n" "\n" "# If the e-mail headers are in a file, uncomment these two lines:\n" "# with open(messagefile, 'rb') as fp:\n" "# headers = BytesParser(policy=default).parse(fp)\n" "\n" "# Or for parsing headers in a string (this is an uncommon operation), use:\n" "headers = Parser(policy=default).parsestr(\n" " 'From: Foo Bar <[email protected]>\\n'\n" " 'To: <[email protected]>\\n'\n" " 'Subject: Test message\\n'\n" " '\\n'\n" " 'Body would go here\\n')\n" "\n" "# Now the header items can be accessed as a dictionary:\n" "print('To: {}'.format(headers['to']))\n" "print('From: {}'.format(headers['from']))\n" "print('Subject: {}'.format(headers['subject']))\n" "\n" "# You can also access the parts of the addresses:\n" "print('Recipient username: {}'.format(headers['to'].addresses[0].username))\n" "print('Sender name: {}'.format(headers['from'].addresses[0].display_name))\n" msgstr "" "# 必要な email モジュールをインポートします\n" "#from email.parser import BytesParser\n" "from email.parser import Parser\n" "from email.policy import default\n" "\n" "# 電子メールのヘッダーがファイルにある場合、次の 2 行のコメントを外します:\n" "# with open(messagefile, 'rb') as fp:\n" "# headers = BytesParser(policy=default).parse(fp)\n" "\n" "# 文字列中のヘッダーを解析する場合 (一般的ではありません) は、次のようにしま" "す:\n" "headers = Parser(policy=default).parsestr(\n" " 'From: Foo Bar <[email protected]>\\n'\n" " 'To: <[email protected]>\\n'\n" " 'Subject: Test message\\n'\n" " '\\n'\n" " 'Body would go here\\n')\n" "\n" "# これで、辞書としてヘッダーの各項目にアクセスできます:\n" "print('To: {}'.format(headers['to']))\n" "print('From: {}'.format(headers['from']))\n" "print('Subject: {}'.format(headers['subject']))\n" "\n" "# アドレスの各部分にもアクセスできます:\n" "print('Recipient username: {}'.format(headers['to'].addresses[0].username))\n" "print('Sender name: {}'.format(headers['from'].addresses[0].display_name))\n" #: ../../library/email.examples.rst:21 msgid "" "Here's an example of how to send a MIME message containing a bunch of family " "pictures that may be residing in a directory:" msgstr "" "つぎに、あるディレクトリ内にある何枚かの家族写真をひとつの MIME メッセージに" "収めて送信する例です:" #: ../../library/email.examples.rst:24 msgid "" "# Import smtplib for the actual sending function.\n" "import smtplib\n" "\n" "# Here are the email package modules we'll need.\n" "from email.message import EmailMessage\n" "\n" "# Create the container email message.\n" "msg = EmailMessage()\n" "msg['Subject'] = 'Our family reunion'\n" "# me == the sender's email address\n" "# family = the list of all recipients' email addresses\n" "msg['From'] = me\n" "msg['To'] = ', '.join(family)\n" "msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" "\n" "# Open the files in binary mode. You can also omit the subtype\n" "# if you want MIMEImage to guess it.\n" "for file in pngfiles:\n" " with open(file, 'rb') as fp:\n" " img_data = fp.read()\n" " msg.add_attachment(img_data, maintype='image',\n" " subtype='png')\n" "\n" "# Send the email via our own SMTP server.\n" "with smtplib.SMTP('localhost') as s:\n" " s.send_message(msg)\n" msgstr "" #: ../../library/email.examples.rst:27 msgid "" "Here's an example of how to send the entire contents of a directory as an " "email message: [1]_" msgstr "" "つぎはあるディレクトリに含まれている内容全体をひとつの電子メールメッセージと" "して送信するやり方です: [1]_" msgid "" "#!/usr/bin/env python3\n" "\n" "\"\"\"Send the contents of a directory as a MIME message.\"\"\"\n" "\n" "import os\n" "import smtplib\n" "# For guessing MIME type based on file name extension\n" "import mimetypes\n" "\n" "from argparse import ArgumentParser\n" "\n" "from email.message import EmailMessage\n" "from email.policy import SMTP\n" "\n" "\n" "def main():\n" " parser = ArgumentParser(description=\"\"\"\\\n" "Send the contents of a directory as a MIME message.\n" "Unless the -o option is given, the email is sent by forwarding to your " "local\n" "SMTP server, which then does the normal delivery process. Your local " "machine\n" "must be running an SMTP server.\n" "\"\"\")\n" " parser.add_argument('-d', '--directory',\n" " help=\"\"\"Mail the contents of the specified " "directory,\n" " otherwise use the current directory. Only the " "regular\n" " files in the directory are sent, and we don't " "recurse to\n" " subdirectories.\"\"\")\n" " parser.add_argument('-o', '--output',\n" " metavar='FILE',\n" " help=\"\"\"Print the composed message to FILE " "instead of\n" " sending the message to the SMTP server.\"\"\")\n" " parser.add_argument('-s', '--sender', required=True,\n" " help='The value of the From: header (required)')\n" " parser.add_argument('-r', '--recipient', required=True,\n" " action='append', metavar='RECIPIENT',\n" " default=[], dest='recipients',\n" " help='A To: header value (at least one required)')\n" " args = parser.parse_args()\n" " directory = args.directory\n" " if not directory:\n" " directory = '.'\n" " # Create the message\n" " msg = EmailMessage()\n" " msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'\n" " msg['To'] = ', '.join(args.recipients)\n" " msg['From'] = args.sender\n" " msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" "\n" " for filename in os.listdir(directory):\n" " path = os.path.join(directory, filename)\n" " if not os.path.isfile(path):\n" " continue\n" " # Guess the content type based on the file's extension. Encoding\n" " # will be ignored, although we should check for simple things like\n" " # gzip'd or compressed files.\n" " ctype, encoding = mimetypes.guess_file_type(path)\n" " if ctype is None or encoding is not None:\n" " # No guess could be made, or the file is encoded (compressed), " "so\n" " # use a generic bag-of-bits type.\n" " ctype = 'application/octet-stream'\n" " maintype, subtype = ctype.split('/', 1)\n" " with open(path, 'rb') as fp:\n" " msg.add_attachment(fp.read(),\n" " maintype=maintype,\n" " subtype=subtype,\n" " filename=filename)\n" " # Now send or store the message\n" " if args.output:\n" " with open(args.output, 'wb') as fp:\n" " fp.write(msg.as_bytes(policy=SMTP))\n" " else:\n" " with smtplib.SMTP('localhost') as s:\n" " s.send_message(msg)\n" "\n" "\n" "if __name__ == '__main__':\n" " main()\n" msgstr "" "#!/usr/bin/env python3\n" "\n" "\"\"\"ディレクトリの内容を MIME メッセージとして送信します。\"\"\"\n" "\n" "import os\n" "import smtplib\n" "# ファイル名の拡張子から MIME 型を推測するために使います\n" "import mimetypes\n" "\n" "from argparse import ArgumentParser\n" "\n" "from email.message import EmailMessage\n" "from email.policy import SMTP\n" "\n" "\n" "def main():\n" " parser = ArgumentParser(description=\"\"\"\\\n" "Send the contents of a directory as a MIME message.\n" "Unless the -o option is given, the email is sent by forwarding to your " "local\n" "SMTP server, which then does the normal delivery process. Your local " "machine\n" "must be running an SMTP server.\n" "\"\"\")\n" " parser.add_argument('-d', '--directory',\n" " help=\"\"\"Mail the contents of the specified " "directory,\n" " otherwise use the current directory. Only the " "regular\n" " files in the directory are sent, and we don't " "recurse to\n" " subdirectories.\"\"\")\n" " parser.add_argument('-o', '--output',\n" " metavar='FILE',\n" " help=\"\"\"Print the composed message to FILE " "instead of\n" " sending the message to the SMTP server.\"\"\")\n" " parser.add_argument('-s', '--sender', required=True,\n" " help='The value of the From: header (required)')\n" " parser.add_argument('-r', '--recipient', required=True,\n" " action='append', metavar='RECIPIENT',\n" " default=[], dest='recipients',\n" " help='A To: header value (at least one required)')\n" " args = parser.parse_args()\n" " directory = args.directory\n" " if not directory:\n" " directory = '.'\n" " # メッセージを作成します\n" " msg = EmailMessage()\n" " msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'\n" " msg['To'] = ', '.join(args.recipients)\n" " msg['From'] = args.sender\n" " msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" "\n" " for filename in os.listdir(directory):\n" " path = os.path.join(directory, filename)\n" " if not os.path.isfile(path):\n" " continue\n" " # ファイルの拡張子からコンテントタイプを推測します。\n" " # エンコーディングは無視しますが、本来は gzip などで圧縮された\n" " # ファイルのような単純なケースを確認する必要があります。\n" " ctype, encoding = mimetypes.guess_file_type(path)\n" " if ctype is None or encoding is not None:\n" " # 推測できなかったか、ファイルがエンコード (圧縮) されているの" "で、\n" " # 汎用のバイナリデータ型を使います。\n" " ctype = 'application/octet-stream'\n" " maintype, subtype = ctype.split('/', 1)\n" " with open(path, 'rb') as fp:\n" " msg.add_attachment(fp.read(),\n" " maintype=maintype,\n" " subtype=subtype,\n" " filename=filename)\n" " # メッセージを送信または保存します\n" " if args.output:\n" " with open(args.output, 'wb') as fp:\n" " fp.write(msg.as_bytes(policy=SMTP))\n" " else:\n" " with smtplib.SMTP('localhost') as s:\n" " s.send_message(msg)\n" "\n" "\n" "if __name__ == '__main__':\n" " main()\n" #: ../../library/email.examples.rst:33 msgid "" "Here's an example of how to unpack a MIME message like the one above, into a " "directory of files:" msgstr "" "つぎに、上のような MIME メッセージをどうやって展開してひとつのディレクトリ上" "の複数ファイルにするかを示します:" msgid "" "#!/usr/bin/env python3\n" "\n" "\"\"\"Unpack a MIME message into a directory of files.\"\"\"\n" "\n" "import os\n" "import email\n" "import mimetypes\n" "\n" "from email.policy import default\n" "\n" "from argparse import ArgumentParser\n" "\n" "\n" "def main():\n" " parser = ArgumentParser(description=\"\"\"\\\n" "Unpack a MIME message into a directory of files.\n" "\"\"\")\n" " parser.add_argument('-d', '--directory', required=True,\n" " help=\"\"\"Unpack the MIME message into the named\n" " directory, which will be created if it doesn't " "already\n" " exist.\"\"\")\n" " parser.add_argument('msgfile')\n" " args = parser.parse_args()\n" "\n" " with open(args.msgfile, 'rb') as fp:\n" " msg = email.message_from_binary_file(fp, policy=default)\n" "\n" " try:\n" " os.mkdir(args.directory)\n" " except FileExistsError:\n" " pass\n" "\n" " counter = 1\n" " for part in msg.walk():\n" " # multipart/* are just containers\n" " if part.get_content_maintype() == 'multipart':\n" " continue\n" " # Applications should really sanitize the given filename so that an\n" " # email message can't be used to overwrite important files\n" " filename = part.get_filename()\n" " if not filename:\n" " ext = mimetypes.guess_extension(part.get_content_type())\n" " if not ext:\n" " # Use a generic bag-of-bits extension\n" " ext = '.bin'\n" " filename = f'part-{counter:03d}{ext}'\n" " counter += 1\n" " with open(os.path.join(args.directory, filename), 'wb') as fp:\n" " fp.write(part.get_payload(decode=True))\n" "\n" "\n" "if __name__ == '__main__':\n" " main()\n" msgstr "" "#!/usr/bin/env python3\n" "\n" "\"\"\"MIME メッセージをディレクトリ内のファイルに展開します。\"\"\"\n" "\n" "import os\n" "import email\n" "import mimetypes\n" "\n" "from email.policy import default\n" "\n" "from argparse import ArgumentParser\n" "\n" "\n" "def main():\n" " parser = ArgumentParser(description=\"\"\"\\\n" "Unpack a MIME message into a directory of files.\n" "\"\"\")\n" " parser.add_argument('-d', '--directory', required=True,\n" " help=\"\"\"Unpack the MIME message into the named\n" " directory, which will be created if it doesn't " "already\n" " exist.\"\"\")\n" " parser.add_argument('msgfile')\n" " args = parser.parse_args()\n" "\n" " with open(args.msgfile, 'rb') as fp:\n" " msg = email.message_from_binary_file(fp, policy=default)\n" "\n" " try:\n" " os.mkdir(args.directory)\n" " except FileExistsError:\n" " pass\n" "\n" " counter = 1\n" " for part in msg.walk():\n" " # multipart/* は単なるコンテナです\n" " if part.get_content_maintype() == 'multipart':\n" " continue\n" " # メールメッセージによって重要なファイルが上書きされないように、\n" " # 実際のアプリケーションではファイル名を安全なものにする必要がありま" "す\n" " filename = part.get_filename()\n" " if not filename:\n" " ext = mimetypes.guess_extension(part.get_content_type())\n" " if not ext:\n" " # 汎用のバイナリデータ用拡張子を使います\n" " ext = '.bin'\n" " filename = f'part-{counter:03d}{ext}'\n" " counter += 1\n" " with open(os.path.join(args.directory, filename), 'wb') as fp:\n" " fp.write(part.get_payload(decode=True))\n" "\n" "\n" "if __name__ == '__main__':\n" " main()\n" #: ../../library/email.examples.rst:39 msgid "" "Here's an example of how to create an HTML message with an alternative plain " "text version. To make things a bit more interesting, we include a related " "image in the html part, and we save a copy of what we are going to send to " "disk, as well as sending it." msgstr "" "代替のプレーンテキストバージョン付きの HTML メッセージを作成する方法の例で" "す。もう少し面白くするために、 HTML 部分に関連する画像を追加し、さらに送信だ" "けでなく、送信しようとしているもののコピーをディスクにも保存してみます。" msgid "" "#!/usr/bin/env python3\n" "\n" "import smtplib\n" "\n" "from email.message import EmailMessage\n" "from email.headerregistry import Address\n" "from email.utils import make_msgid\n" "\n" "# Create the base text message.\n" "msg = EmailMessage()\n" "msg['Subject'] = \"Pourquoi pas des asperges pour ce midi ?\"\n" "msg['From'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\n" "msg['To'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\n" " Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\n" "msg.set_content(\"\"\"\\\n" "Salut!\n" "\n" "Cette recette [1] sera sûrement un très bon repas.\n" "\n" "[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" "\n" "--Pepé\n" "\"\"\")\n" "\n" "# Add the html version. This converts the message into a multipart/" "alternative\n" "# container, with the original text message as the first part and the new " "html\n" "# message as the second part.\n" "asparagus_cid = make_msgid()\n" "msg.add_alternative(\"\"\"\\\n" "<html>\n" " <head></head>\n" " <body>\n" " <p>Salut!</p>\n" " <p>Cette\n" " <a href=\"http://www.yummly.com/recipe/Roasted-Asparagus-" "Epicurious-203718\">\n" " recette\n" " </a> sera sûrement un très bon repas.\n" " </p>\n" " <img src=\"cid:{asparagus_cid}\">\n" " </body>\n" "</html>\n" "\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')\n" "# note that we needed to peel the <> off the msgid for use in the html.\n" "\n" "# Now add the related image to the html part.\n" "with open(\"roasted-asparagus.jpg\", 'rb') as img:\n" " msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',\n" " cid=asparagus_cid)\n" "\n" "# Make a local copy of what we are going to send.\n" "with open('outgoing.msg', 'wb') as f:\n" " f.write(bytes(msg))\n" "\n" "# Send the message via local SMTP server.\n" "with smtplib.SMTP('localhost') as s:\n" " s.send_message(msg)\n" msgstr "" "#!/usr/bin/env python3\n" "\n" "import smtplib\n" "\n" "from email.message import EmailMessage\n" "from email.headerregistry import Address\n" "from email.utils import make_msgid\n" "\n" "# 基本のテキストメッセージを作成します。\n" "msg = EmailMessage()\n" "msg['Subject'] = \"Pourquoi pas des asperges pour ce midi ?\"\n" "msg['From'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\n" "msg['To'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\n" " Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\n" "msg.set_content(\"\"\"\\\n" "Salut!\n" "\n" "Cette recette [1] sera sûrement un très bon repas.\n" "\n" "[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" "\n" "--Pepé\n" "\"\"\")\n" "\n" "# HTML 版を追加します。\n" "# メッセージは multipart/alternative コンテナになり、\n" "# 最初のパートが元のテキストメッセージ、\n" "# 2 番目のパートが新しい HTML メッセージになります。\n" "asparagus_cid = make_msgid()\n" "msg.add_alternative(\"\"\"\\\n" "<html>\n" " <head></head>\n" " <body>\n" " <p>Salut!</p>\n" " <p>Cette\n" " <a href=\"http://www.yummly.com/recipe/Roasted-Asparagus-" "Epicurious-203718\">\n" " recette\n" " </a> sera sûrement un très bon repas.\n" " </p>\n" " <img src=\"cid:{asparagus_cid}\">\n" " </body>\n" "</html>\n" "\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')\n" "# HTML で使うために msgid から <> を取り除く必要がある点に注意してくださ" "い。\n" "\n" "# HTML パートに関連する画像を追加します。\n" "with open(\"roasted-asparagus.jpg\", 'rb') as img:\n" " msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',\n" " cid=asparagus_cid)\n" "\n" "# 送信する内容のローカルコピーを作成します。\n" "with open('outgoing.msg', 'wb') as f:\n" " f.write(bytes(msg))\n" "\n" "# ローカル SMTP サーバー経由でメッセージを送信します。\n" "with smtplib.SMTP('localhost') as s:\n" " s.send_message(msg)\n" #: ../../library/email.examples.rst:47 msgid "" "If we were sent the message from the last example, here is one way we could " "process it:" msgstr "" "前の例のメッセージが送信されてきたら、これを処理する方法の一つは次のようなも" "のです:" msgid "" "import os\n" "import sys\n" "import tempfile\n" "import mimetypes\n" "import webbrowser\n" "\n" "# Import the email modules we'll need\n" "from email import policy\n" "from email.parser import BytesParser\n" "\n" "\n" "def magic_html_parser(html_text, partfiles):\n" " \"\"\"Return safety-sanitized html linked to partfiles.\n" "\n" " Rewrite the href=\"cid:....\" attributes to point to the filenames in " "partfiles.\n" " Though not trivial, this should be possible using html.parser.\n" " \"\"\"\n" " raise NotImplementedError(\"Add the magic needed\")\n" "\n" "\n" "# In a real program you'd get the filename from the arguments.\n" "with open('outgoing.msg', 'rb') as fp:\n" " msg = BytesParser(policy=policy.default).parse(fp)\n" "\n" "# Now the header items can be accessed as a dictionary, and any non-ASCII " "will\n" "# be converted to unicode:\n" "print('To:', msg['to'])\n" "print('From:', msg['from'])\n" "print('Subject:', msg['subject'])\n" "\n" "# If we want to print a preview of the message content, we can extract " "whatever\n" "# the least formatted payload is and print the first three lines. Of " "course,\n" "# if the message has no plain text part printing the first three lines of " "html\n" "# is probably useless, but this is just a conceptual example.\n" "simplest = msg.get_body(preferencelist=('plain', 'html'))\n" "print()\n" "print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))\n" "\n" "ans = input(\"View full message?\")\n" "if ans.lower()[0] == 'n':\n" " sys.exit()\n" "\n" "# We can extract the richest alternative in order to display it:\n" "richest = msg.get_body()\n" "partfiles = {}\n" "if richest['content-type'].maintype == 'text':\n" " if richest['content-type'].subtype == 'plain':\n" " for line in richest.get_content().splitlines():\n" " print(line)\n" " sys.exit()\n" " elif richest['content-type'].subtype == 'html':\n" " body = richest\n" " else:\n" " print(\"Don't know how to display {}" "\".format(richest.get_content_type()))\n" " sys.exit()\n" "elif richest['content-type'].content_type == 'multipart/related':\n" " body = richest.get_body(preferencelist=('html'))\n" " for part in richest.iter_attachments():\n" " fn = part.get_filename()\n" " if fn:\n" " extension = os.path.splitext(part.get_filename())[1]\n" " else:\n" " extension = mimetypes.guess_extension(part.get_content_type())\n" " with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as " "f:\n" " f.write(part.get_content())\n" " # again strip the <> to go from email form of cid to html form.\n" " partfiles[part['content-id'][1:-1]] = f.name\n" "else:\n" " print(\"Don't know how to display {}" "\".format(richest.get_content_type()))\n" " sys.exit()\n" "with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:\n" " f.write(magic_html_parser(body.get_content(), partfiles))\n" "webbrowser.open(f.name)\n" "os.remove(f.name)\n" "for fn in partfiles.values():\n" " os.remove(fn)\n" "\n" "# Of course, there are lots of email messages that could break this simple\n" "# minded program, but it will handle the most common ones.\n" msgstr "" "import os\n" "import sys\n" "import tempfile\n" "import mimetypes\n" "import webbrowser\n" "\n" "# 必要な email モジュールをインポートします\n" "from email import policy\n" "from email.parser import BytesParser\n" "\n" "\n" "def magic_html_parser(html_text, partfiles):\n" " \"\"\"安全性に配慮して処理し、partfiles にリンクする HTML を返します。\n" "\n" " href=\"cid:....\" 属性を書き換え、partfiles 内のファイル名を指すようにし" "ます。\n" " 簡単ではありませんが、html.parser を使えば実現できるはずです。\n" " \"\"\"\n" " raise NotImplementedError(\"Add the magic needed\")\n" "\n" "\n" "# 実際のプログラムでは、引数からファイル名を取得します。\n" "with open('outgoing.msg', 'rb') as fp:\n" " msg = BytesParser(policy=policy.default).parse(fp)\n" "\n" "# これでヘッダーの各項目に辞書としてアクセスでき、\n" "# 非 ASCII 文字は Unicode に変換されます:\n" "print('To:', msg['to'])\n" "print('From:', msg['from'])\n" "print('Subject:', msg['subject'])\n" "\n" "# メッセージ内容のプレビューを表示するには、最も書式の少ないペイロードを\n" "# 取り出して最初の 3 行を表示できます。\n" "# もちろん、プレーンテキストのパートが\n" "# なければ HTML の最初の 3 行を表示してもあまり役に立ちませんが、\n" "# ここでは考え方を示すための例としています。\n" "simplest = msg.get_body(preferencelist=('plain', 'html'))\n" "print()\n" "print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))\n" "\n" "ans = input(\"View full message?\")\n" "if ans.lower()[0] == 'n':\n" " sys.exit()\n" "\n" "# 表示のために最も情報の豊かな代替パートを取り出せます:\n" "richest = msg.get_body()\n" "partfiles = {}\n" "if richest['content-type'].maintype == 'text':\n" " if richest['content-type'].subtype == 'plain':\n" " for line in richest.get_content().splitlines():\n" " print(line)\n" " sys.exit()\n" " elif richest['content-type'].subtype == 'html':\n" " body = richest\n" " else:\n" " print(\"Don't know how to display {}" "\".format(richest.get_content_type()))\n" " sys.exit()\n" "elif richest['content-type'].content_type == 'multipart/related':\n" " body = richest.get_body(preferencelist=('html'))\n" " for part in richest.iter_attachments():\n" " fn = part.get_filename()\n" " if fn:\n" " extension = os.path.splitext(part.get_filename())[1]\n" " else:\n" " extension = mimetypes.guess_extension(part.get_content_type())\n" " with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as " "f:\n" " f.write(part.get_content())\n" " # ここでも <> を除いて、メール形式の cid を HTML 形式にします。\n" " partfiles[part['content-id'][1:-1]] = f.name\n" "else:\n" " print(\"Don't know how to display {}" "\".format(richest.get_content_type()))\n" " sys.exit()\n" "with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:\n" " f.write(magic_html_parser(body.get_content(), partfiles))\n" "webbrowser.open(f.name)\n" "os.remove(f.name)\n" "for fn in partfiles.values():\n" " os.remove(fn)\n" "\n" "# もちろん、この単純なプログラムでは扱えないメッセージも数多くありますが、\n" "# よくあるメッセージには対応できます。\n" #: ../../library/email.examples.rst:52 msgid "Up to the prompt, the output from the above is:" msgstr "プロンプトまでの、上記のプログラムの出力はこうなります:" msgid "" "To: Penelope Pussycat <[email protected]>, Fabrette Pussycat " "<[email protected]>\n" "From: Pepé Le Pew <[email protected]>\n" "Subject: Pourquoi pas des asperges pour ce midi ?\n" "\n" "Salut!\n" "\n" "Cette recette [1] sera sûrement un très bon repas." msgstr "" "To: Penelope Pussycat <[email protected]>, Fabrette Pussycat " "<[email protected]>\n" "From: Pepé Le Pew <[email protected]>\n" "Subject: Pourquoi pas des asperges pour ce midi ?\n" "\n" "Salut!\n" "\n" "Cette recette [1] sera sûrement un très bon repas." #: ../../library/email.examples.rst:66 msgid "Footnotes" msgstr "脚注" #: ../../library/email.examples.rst:67 msgid "" "Thanks to Matthew Dixon Cowles for the original inspiration and examples." msgstr "最初の思いつきと用例は Matthew Dixon Cowles のおかげです。" |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |