⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch18_04.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 18.3. Sending Mail (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:45:01Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch18_01.htm"TITLE="18. Internet Services"><LINKREL="prev"HREF="ch18_03.htm"TITLE="18.2. Being an FTP Client"><LINKREL="next"HREF="ch18_05.htm"TITLE="18.4. Reading and Posting Usenet News Messages"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch18_03.htm"TITLE="18.2. Being an FTP Client"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 18.2. Being an FTP Client"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch18_01.htm"TITLE="18. Internet Services"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch18_05.htm"TITLE="18.4. Reading and Posting Usenet News Messages"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 18.4. Reading and Posting Usenet News Messages"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch18-27351">18.3. Sending Mail</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch18-pgfId-399">Problem</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch18-idx-1000004293-0"></A><ACLASS="indexterm"NAME="ch18-idx-1000004293-1"></A><ACLASS="indexterm"NAME="ch18-idx-1000004293-2"></A>You want your program to send mail. Some programs monitor system resources like disk space and notify appropriate people by mail when disk space becomes dangerously low. CGI script authors may not want their programs to report errors like "the database is down" to the user, preferring instead to send mail to the database administrator notifying them of the problem.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch18-pgfId-405">Solution</A></H3><PCLASS="para">Use the CPAN module Mail::Mailer:</P><PRECLASS="programlisting">use Mail::Mailer;$mailer = Mail::Mailer-&gt;new(&quot;sendmail&quot;);$mailer-&gt;open({ From    =&gt; $from_address,                To      =&gt; $to_address,                Subject =&gt; $subject,              })    or die &quot;Can't open: $!\n&quot;;print $mailer $body;$mailer-&gt;<CODECLASS="literal">close();</CODE></PRE><PCLASS="para">Or, use the <CODECLASS="literal">sendmail</CODE> program directly:</P><PRECLASS="programlisting">open(SENDMAIL, &quot;|/usr/lib/sendmail -oi -t -odq&quot;)                    or die &quot;Can't fork for sendmail: $!\n&quot;;print SENDMAIL &lt;&lt;&quot;EOF&quot;;From: User Originating Mail &lt;me\@host&gt;To: Final Destination &lt;you\@otherhost&gt;Subject: A relevant subject lineBody of the message goes here, in as many lines as you like.EOFclose(SENDMAIL)     or warn &quot;sendmail didn't close nicely&quot;;</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch18-pgfId-453">Discussion</A></H3><PCLASS="para">You have three choices for sending mail from your program. You can use another program that users normally use to send mail, like <EMCLASS="emphasis">Mail</EM> or <EMCLASS="emphasis">mailx </EM>; these are called MUAs or <EMCLASS="emphasis">Mail User Agents</EM>. You can use a system-level mail program like <EMCLASS="emphasis">sendmail </EM>; this is an MTA, or <EMCLASS="emphasis">Mail Transport Agent</EM>. Or you can connect to an SMTP (Simple Mail Transfer Protocol) server. Unfortunately, there's no standard user-level mail program, <EMCLASS="emphasis">sendmail</EM> doesn't have a standard location, and SMTP isn't particularly simple. The CPAN module Mail::Mailer hides these complexities from you.</P><PCLASS="para">When Mail::Mailer is installed, it looks for <EMCLASS="emphasis">mail</EM>, <EMCLASS="emphasis">Mail</EM>, and other names mail-sending programs tend to hide under. It also looks in common locations for <EMCLASS="emphasis">sendmail</EM>. When you create a Mail::Mailer object, you get convenient access to those programs (and SMTP mail servers) without needing to know their argument structure or how they return errors.</P><PCLASS="para">Create a Mail::Mailer object with <CODECLASS="literal">Mail::Mailer-&gt;new</CODE>. If you don't pass any arguments, it uses the default mail sending method (probably a program like <EMCLASS="emphasis">mail </EM>). Arguments to <CODECLASS="literal">new</CODE> let you pick an alternative way of sending the message. The first argument is the type of delivery method (<CODECLASS="literal">&quot;mail&quot;</CODE> for a Unix mail user agent, <CODECLASS="literal">&quot;sendmail&quot;</CODE> for sendmail, and <CODECLASS="literal">&quot;smtp&quot;</CODE> to open a connection to an SMTP server). The optional second argument is the path to the program.</P><PCLASS="para">For instance, here is how to instruct Mail::Mailer to use <EMCLASS="emphasis">sendmail</EM> instead of its default:</P><PRECLASS="programlisting">$mailer = Mail::Mailer-&gt;new(&quot;sendmail&quot;);</PRE><PCLASS="para">Here's how to tell it to use <CODECLASS="literal">/u/gnat/bin/funkymailer</CODE> instead of <EMCLASS="emphasis">mail</EM>:</P><PRECLASS="programlisting">$mailer = Mail::Mailer-&gt;new(&quot;mail&quot;, &quot;/u/gnat/bin/funkymailer&quot;);</PRE><PCLASS="para">Here's how to use SMTP with the machine <EMCLASS="emphasis">mail.myisp.com</EM> as the mail server:</P><PRECLASS="programlisting">$mailer = Mail::Mailer-&gt;new(&quot;smtp&quot;, &quot;mail.myisp.com&quot;);</PRE><PCLASS="para">If an error occurs at any part of Mail::Mailer, <CODECLASS="literal">die</CODE> is called. This means if you want to check for errors, you need to wrap your mail-sending code in <CODECLASS="literal">eval</CODE> and check <CODECLASS="literal">$@</CODE> afterward:</P><PRECLASS="programlisting">eval {    $mailer = Mail::Mailer-&gt;new(&quot;bogus&quot;, &quot;arguments&quot;);    # ...};if ($@) {    # the eval failed    print &quot;Couldn't send mail: $@\n&quot;;} else {    # the eval succeeded    print &quot;The authorities have been notified.\n&quot;;}</PRE><PCLASS="para">The <CODECLASS="literal">new</CODE> constructor raises an exception if you provide arguments it doesn't understand or if you specify no arguments and it doesn't have a default method. Mail::Mailer won't run a program or connect to the SMTP server until you call the <CODECLASS="literal">open</CODE> method with the headers of the message:</P><PRECLASS="programlisting">$mailer-&gt;open( 'From'    =&gt; 'Nathan Torkington &lt;gnat@frii.com&gt;',               'To'      =&gt; 'Tom Christiansen &lt;tchrist@perl.com&gt;',               'Subject' =&gt; 'The Perl Cookbook' );</PRE><PCLASS="para">The <CODECLASS="literal">open</CODE> method raises an exception if the program or server couldn't be opened. If <CODECLASS="literal">open</CODE> succeeds, you may treat <CODECLASS="literal">$mailer</CODE> as a filehandle and print the body of your message to it:</P><PRECLASS="programlisting">print $mailer &lt;&lt;EO_SIG;Are we ever going to finish this book?My wife is threatening to leave me.She says I love EMACS more than I love her.Do you have a recipe that can help me?NatEO_SIG</PRE><PCLASS="para">When you're done, call the <CODECLASS="literal">close</CODE> function on the Mail::Mailer object:</P><PRECLASS="programlisting">close($mailer)                      or die &quot;can't close mailer: $!&quot;;</PRE><PCLASS="para">If you want to go it alone and communicate with <EMCLASS="emphasis">sendmail</EM> directly, use something like this:</P><PRECLASS="programlisting">open(SENDMAIL, &quot;|/usr/sbin/sendmail -oi -t -odq&quot;)            or die &quot;Can't fork for sendmail: $!\n&quot;;print SENDMAIL &lt;&lt;&quot;EOF&quot;;From: Tom Christiansen &lt;tchrist\@perl.com&gt;To: Nathan Torkington &lt;gnat\@frii.com&gt;Subject: Re: The Perl Cookbook(1) We will never finish the book.(2) No man who uses EMACS is deserving of love.(3) I recommend coq au vi.tomEOFclose(SENDMAIL);</PRE><PCLASS="para">This is a straightforward use of <CODECLASS="literal">open</CODE> to run another program (see <ACLASS="xref"HREF="ch16_05.htm"TITLE="Reading or Writing to Another Program">Recipe 16.4</A>). You need to specify the full path to <CODECLASS="literal">sendmail</CODE> because its location varies from machine to machine. It is often found in places like <ICLASS="filename">/usr/lib</I> or <ICLASS="filename">/usr/sbin</I>. The flags we give to <EMCLASS="emphasis">sendmail</EM> say to not exit when a line with only a dot is read (<CODECLASS="literal">-oi</CODE>), to read the headers of the message to decide whom to send it to (<CODECLASS="literal">-t</CODE>), and to insert the message into the queue instead of attempting to deliver it immediately (<CODECLASS="literal">-odq</CODE>). This last option is only important when you're sending a lot of mail &nbsp;-  omitting it would quickly swamp the machine with <EMCLASS="emphasis">sendmail</EM> processes. If you want immediate delivery of your message (for instance, you're testing your program or the mail is urgent) remove <CODECLASS="literal">-odq</CODE> from the command line.</P><PCLASS="para">We <CODECLASS="literal">print</CODE> an entire message, headers and then body, separated by a blank line. There are no special escapes to insert new lines (as some user mail programs have), so all text is literal. <EMCLASS="emphasis">sendmail</EM> adds headers like <CODECLASS="literal">Date</CODE> and <CODECLASS="literal">Message-ID</CODE> (which you shouldn't generate yourself anyway).</P><PCLASS="para">Some ports of Perl (Windows and Mac particularly) don't have <EMCLASS="emphasis">sendmail</EM> or <EMCLASS="emphasis">mail</EM> to use. In these cases, you should find an SMTP server you can send mail through.<ACLASS="indexterm"NAME="ch18-idx-1000004295-0"></A><ACLASS="indexterm"NAME="ch18-idx-1000004295-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch18-pgfId-1000004530">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">open</CODE> function in <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and in <ICLASS="filename">perlfunc </I>(1); <ACLASS="xref"HREF="ch16_05.htm"TITLE="Reading or Writing to Another Program">Recipe 16.4</A>; <ACLASS="xref"HREF="ch16_11.htm"TITLE="Communicating Between Related Processes">Recipe 16.10</A>; <ACLASS="xref"HREF="ch16_20.htm"TITLE="Avoiding Zombie Processes">Recipe 16.19</A>; <ACLASS="xref"HREF="ch19_07.htm"TITLE="Executing Commands Without Shell Escapes">Recipe 19.6</A>; the RFCs dictating the SMTP protocol, RFC 821, <CITECLASS="citetitle">Simple Mail Transfer Protocol</CITE>, as amended by later RFCs</P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch18_03.htm"TITLE="18.2. Being an FTP Client"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 18.2. Being an FTP Client"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch18_05.htm"TITLE="18.4. Reading and Posting Usenet News Messages"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 18.4. Reading and Posting Usenet News Messages"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">18.2. Being an FTP Client</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">18.4. Reading and Posting Usenet News Messages</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -