This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldiag: rewording
[perl5.git] / pod / perlfaq9.pod
CommitLineData
68dc0745 1=head1 NAME
2
109f0441 3perlfaq9 - Networking
68dc0745 4
5=head1 DESCRIPTION
6
7This section deals with questions related to networking, the internet,
8and a few on the web.
9
24f1ba9b 10=head2 What is the correct form of response from a CGI script?
68dc0745 11
24f1ba9b
JH
12(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
13
197aec24
RGS
14The Common Gateway Interface (CGI) specifies a software interface between
15a program ("CGI script") and a web server (HTTPD). It is not specific
16to Perl, and has its own FAQs and tutorials, and usenet group,
17comp.infosystems.www.authoring.cgi
24f1ba9b 18
6670e5e7
RGS
19The CGI specification is outlined in an informational RFC:
20http://www.ietf.org/rfc/rfc3875
24f1ba9b 21
197aec24 22These Perl FAQs very selectively cover some CGI issues. However, Perl
589a5df2 23programmers are strongly advised to use the C<CGI.pm> module, to take care
197aec24 24of the details for them.
68dc0745 25
24f1ba9b
JH
26The similarity between CGI response headers (defined in the CGI
27specification) and HTTP response headers (defined in the HTTP
28specification, RFC2616) is intentional, but can sometimes be confusing.
68dc0745 29
24f1ba9b
JH
30The CGI specification defines two kinds of script: the "Parsed Header"
31script, and the "Non Parsed Header" (NPH) script. Check your server
32documentation to see what it supports. "Parsed Header" scripts are
33simpler in various respects. The CGI specification allows any of the
34usual newline representations in the CGI response (it's the server's
35job to create an accurate HTTP response based on it). So "\n" written in
36text mode is technically correct, and recommended. NPH scripts are more
37tricky: they must put out a complete and accurate set of HTTP
38transaction response headers; the HTTP specification calls for records
39to be terminated with carriage-return and line-feed, i.e ASCII \015\012
40written in binary mode.
68dc0745 41
589a5df2 42Using C<CGI.pm> gives excellent platform independence, including EBCDIC
43systems. C<CGI.pm> selects an appropriate newline representation
44(C<$CGI::CRLF>) and sets binmode as appropriate.
c8db1d39 45
39150746 46=head2 My CGI script runs from the command line but not the browser. (500 Server Error)
0bc0ad85 47
39150746 48(contributed by brian d foy)
c8db1d39 49
39150746 50There are many things that might be wrong with your CGI program, and only
51some of them might be related to Perl. Try going through the troubleshooting
52guide on Perlmonks:
24f1ba9b 53
39150746 54 http://www.perlmonks.org/?node_id=380424
c8db1d39 55
c8db1d39
TC
56=head2 How can I get better error messages from a CGI program?
57
589a5df2 58Use the C<CGI::Carp> module. It replaces C<warn> and C<die>, plus the
59normal C<Carp> modules C<carp>, C<croak>, and C<confess> functions with
c8db1d39
TC
60more verbose and safer versions. It still sends them to the normal
61server error log.
62
109f0441
S
63 use CGI::Carp;
64 warn "This is a complaint";
65 die "But this one is serious";
c8db1d39 66
589a5df2 67The following use of C<CGI::Carp> also redirects errors to a file of your choice,
68placed in a C<BEGIN> block to catch compile-time warnings as well:
c8db1d39 69
109f0441
S
70 BEGIN {
71 use CGI::Carp qw(carpout);
72 open(LOG, ">>/var/local/cgi-logs/mycgi-log")
73 or die "Unable to append to mycgi-log: $!\n";
74 carpout(*LOG);
75 }
c8db1d39
TC
76
77You can even arrange for fatal errors to go back to the client browser,
78which is nice for your own debugging, but might confuse the end user.
79
109f0441
S
80 use CGI::Carp qw(fatalsToBrowser);
81 die "Bad error here";
c8db1d39
TC
82
83Even if the error happens before you get the HTTP header out, the module
84will try to take care of this to avoid the dreaded server 500 errors.
85Normal warnings still go out to the server error log (or wherever
86you've sent them with C<carpout>) with the application name and date
87stamp prepended.
88
68dc0745 89=head2 How do I remove HTML from a string?
90
589a5df2 91The most correct way (albeit not the fastest) is to use C<HTML::Parser>
bed171df 92from CPAN. Another mostly correct
589a5df2 93way is to use C<HTML::FormatText> which not only removes HTML but also
7d7e76cf 94attempts to do a little simple formatting of the resulting plain text.
68dc0745 95
96Many folks attempt a simple-minded regular expression approach, like
c47ff5f1 97C<< s/<.*?>//g >>, but that fails in many cases because the tags
68dc0745 98may continue over line breaks, they may contain quoted angle-brackets,
a6dd486b
JB
99or HTML comment may be present. Plus, folks forget to convert
100entities--like C<&lt;> for example.
68dc0745 101
102Here's one "simple-minded" approach, that works for most files:
103
109f0441 104 #!/usr/bin/perl -p0777
d8b950dc 105 s/<(?:[^>'"]*|(['"]).*?\g1)*>//gs
68dc0745 106
107If you want a more complete solution, see the 3-stage striphtml
108program in
a93751fa 109http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
68dc0745 110.
111
c8db1d39
TC
112Here are some tricky cases that you should think about when picking
113a solution:
114
109f0441 115 <IMG SRC = "foo.gif" ALT = "A > B">
c8db1d39 116
109f0441 117 <IMG SRC = "foo.gif"
c8db1d39
TC
118 ALT = "A > B">
119
109f0441 120 <!-- <A comment> -->
c8db1d39 121
109f0441 122 <script>if (a<b && a>c)</script>
c8db1d39 123
109f0441 124 <# Just data #>
c8db1d39 125
109f0441 126 <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
c8db1d39
TC
127
128If HTML comments include other tags, those solutions would also break
129on text like this:
130
109f0441
S
131 <!-- This section commented out.
132 <B>You can't see me!</B>
133 -->
c8db1d39 134
68dc0745 135=head2 How do I extract URLs?
136
e67d034e
JH
137You can easily extract all sorts of URLs from HTML with
138C<HTML::SimpleLinkExtor> which handles anchors, images, objects,
197aec24
RGS
139frames, and many other tags that can contain a URL. If you need
140anything more complex, you can create your own subclass of
141C<HTML::LinkExtor> or C<HTML::Parser>. You might even use
e67d034e
JH
142C<HTML::SimpleLinkExtor> as an example for something specifically
143suited to your needs.
144
589a5df2 145You can use C<URI::Find> to extract URLs from an arbitrary text document.
49d635f9 146
197aec24 147Less complete solutions involving regular expressions can save
e67d034e
JH
148you a lot of processing time if you know that the input is simple. One
149solution from Tom Christiansen runs 100 times faster than most
150module based approaches but only extracts URLs from anchors where the first
197aec24 151attribute is HREF and there are no other attributes.
e67d034e 152
109f0441
S
153 #!/usr/bin/perl -n00
154 # qxurl - tchrist@perl.com
155 print "$2\n" while m{
156 < \s*
d8b950dc 157 A \s+ HREF \s* = \s* (["']) (.*?) \g1
109f0441
S
158 \s* >
159 }gsix;
68dc0745 160
161=head2 How do I download a file from the user's machine? How do I open a file on another machine?
162
49d635f9
RGS
163In this case, download means to use the file upload feature of HTML
164forms. You allow the web surfer to specify a file to send to your web
165server. To you it looks like a download, and to the user it looks
166like an upload. No matter what you call it, you do it with what's
589a5df2 167known as B<multipart/form-data> encoding. The C<CGI.pm> module (which
49d635f9 168comes with Perl as part of the Standard Library) supports this in the
589a5df2 169C<start_multipart_form()> method, which isn't the same as the C<startform()>
49d635f9
RGS
170method.
171
589a5df2 172See the section in the C<CGI.pm> documentation on file uploads for code
49d635f9 173examples and details.
68dc0745 174
e573f903
RGS
175=head2 How do I make an HTML pop-up menu with Perl?
176
177(contributed by brian d foy)
178
589a5df2 179The C<CGI.pm> module (which comes with Perl) has functions to create
180the HTML form widgets. See the C<CGI.pm> documentation for more
e573f903
RGS
181examples.
182
183 use CGI qw/:standard/;
184 print header,
185 start_html('Favorite Animals'),
186
187 start_form,
188 "What's your favorite animal? ",
109f0441
S
189 popup_menu(
190 -name => 'animal',
e573f903
RGS
191 -values => [ qw( Llama Alpaca Camel Ram ) ]
192 ),
109f0441 193 submit,
68dc0745 194
109f0441
S
195 end_form,
196 end_html;
68dc0745 197
198=head2 How do I fetch an HTML file?
199
109f0441
S
200(contributed by brian d foy)
201
202Use the libwww-perl distribution. The C<LWP::Simple> module can fetch web
203resources and give their content back to you as a string:
68dc0745 204
109f0441 205 use LWP::Simple qw(get);
68dc0745 206
109f0441 207 my $html = get( "http://www.example.com/index.html" );
46fc3d4c 208
109f0441 209It can also store the resource directly in a file:
c8db1d39 210
109f0441 211 use LWP::Simple qw(getstore);
46fc3d4c 212
109f0441
S
213 getstore( "http://www.example.com/index.html", "foo.html" );
214
215If you need to do something more complicated, you can use
216C<LWP::UserAgent> module to create your own user-agent (e.g. browser)
217to get the job done. If you want to simulate an interactive web
218browser, you can use the C<WWW::Mechanize> module.
46fc3d4c 219
c8db1d39
TC
220=head2 How do I automate an HTML form submission?
221
7678cced
RGS
222If you are doing something complex, such as moving through many pages
223and forms or a web site, you can use C<WWW::Mechanize>. See its
224documentation for all the details.
225
c8db1d39
TC
226If you're submitting values using the GET method, create a URL and encode
227the form using the C<query_form> method:
228
109f0441
S
229 use LWP::Simple;
230 use URI::URL;
c8db1d39 231
109f0441
S
232 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
233 $url->query_form(module => 'DB_File', readme => 1);
234 $content = get($url);
c8db1d39
TC
235
236If you're using the POST method, create your own user agent and encode
237the content appropriately.
238
109f0441
S
239 use HTTP::Request::Common qw(POST);
240 use LWP::UserAgent;
c8db1d39 241
109f0441
S
242 $ua = LWP::UserAgent->new();
243 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
244 [ module => 'DB_File', readme => 1 ];
245 $content = $ua->request($req)->as_string;
c8db1d39
TC
246
247=head2 How do I decode or create those %-encodings on the web?
109f0441
S
248X<URI> X<CGI.pm> X<CGI> X<URI::Escape> X<RFC 2396>
249
250(contributed by brian d foy)
251
252Those C<%> encodings handle reserved characters in URIs, as described
253in RFC 2396, Section 2. This encoding replaces the reserved character
254with the hexadecimal representation of the character's number from
255the US-ASCII table. For instance, a colon, C<:>, becomes C<%3A>.
256
257In CGI scripts, you don't have to worry about decoding URIs if you are
258using C<CGI.pm>. You shouldn't have to process the URI yourself,
259either on the way in or the way out.
68dc0745 260
109f0441
S
261If you have to encode a string yourself, remember that you should
262never try to encode an already-composed URI. You need to escape the
263components separately then put them together. To encode a string, you
e164034b 264can use the C<URI::Escape> module. The C<uri_escape> function
109f0441 265returns the escaped string:
68dc0745 266
109f0441 267 my $original = "Colon : Hash # Percent %";
575cc754 268
3bc3c5be 269 my $escaped = uri_escape( $original );
575cc754 270
3bc3c5be 271 print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25'
575cc754 272
109f0441 273To decode the string, use the C<uri_unescape> function:
575cc754 274
109f0441
S
275 my $unescaped = uri_unescape( $escaped );
276
277 print $unescaped; # back to original
278
279If you wanted to do it yourself, you simply need to replace the
280reserved characters with their encodings. A global substitution
281is one way to do it:
282
283 # encode
284 $string =~ s/([^^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%0x", ord $1 /eg;
285
286 #decode
287 $string =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;
68dc0745 288
289=head2 How do I redirect to another page?
290
24f1ba9b
JH
291Specify the complete URL of the destination (even if it is on the same
292server). This is one of the two different kinds of CGI "Location:"
293responses which are defined in the CGI specification for a Parsed Headers
294script. The other kind (an absolute URLpath) is resolved internally to
295the server without any HTTP redirection. The CGI specifications do not
296allow relative URLs in either case.
297
589a5df2 298Use of C<CGI.pm> is strongly recommended. This example shows redirection
24f1ba9b
JH
299with a complete URL. This redirection is handled by the web browser.
300
109f0441 301 use CGI qw/:standard/;
68dc0745 302
109f0441
S
303 my $url = 'http://www.cpan.org/';
304 print redirect($url);
68dc0745 305
24f1ba9b
JH
306This example shows a redirection with an absolute URLpath. This
307redirection is handled by the local web server.
68dc0745 308
109f0441
S
309 my $url = '/CPAN/index.html';
310 print redirect($url);
d92eb7b0 311
197aec24 312But if coded directly, it could be as follows (the final "\n" is
24f1ba9b 313shown separately, for clarity), using either a complete URL or
197aec24 314an absolute URLpath.
d92eb7b0 315
109f0441
S
316 print "Location: $url\n"; # CGI response header
317 print "\n"; # end of headers
c8db1d39 318
68dc0745 319=head2 How do I put a password on my web pages?
320
49d635f9
RGS
321To enable authentication for your web server, you need to configure
322your web server. The configuration is different for different sorts
ac9dac7f 323of web servers--apache does it differently from iPlanet which does
49d635f9
RGS
324it differently from IIS. Check your web server documentation for
325the details for your particular server.
68dc0745 326
327=head2 How do I edit my .htpasswd and .htgroup files with Perl?
328
589a5df2 329The C<HTTPD::UserAdmin> and C<HTTPD::GroupAdmin> modules provide a
68dc0745 330consistent OO interface to these files, regardless of how they're
426affbf 331stored. Databases may be text, dbm, Berkeley DB or any database with
589a5df2 332a DBI compatible driver. C<HTTPD::UserAdmin> supports files used by the
b432a672 333"Basic" and "Digest" authentication schemes. Here's an example:
68dc0745 334
109f0441
S
335 use HTTPD::UserAdmin ();
336 HTTPD::UserAdmin
68dc0745 337 ->new(DB => "/foo/.htpasswd")
338 ->add($username => $password);
339
46fc3d4c 340=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
341
b67b790e 342(contributed by brian d foy)
46fc3d4c 343
3d38a12c 344You can't prevent people from sending your script bad data. Even if
345you add some client-side checks, people may disable them or bypass
346them completely. For instance, someone might use a module such as
347C<LWP> to access your CGI program. If you want to prevent data that
348try to use SQL injection or other sorts of attacks (and you should
349want to), you have to not trust any data that enter your program.
b67b790e 350
351The L<perlsec> documentation has general advice about data security.
352If you are using the C<DBI> module, use placeholder to fill in data.
353If you are running external programs with C<system> or C<exec>, use
354the list forms. There are many other precautions that you should take,
355too many to list here, and most of them fall under the category of not
356using any data that you don't intend to use. Trust no one.
46fc3d4c 357
5a964f20 358=head2 How do I parse a mail header?
68dc0745 359
360For a quick-and-dirty solution, try this solution derived
b73a15ae 361from L<perlfunc/split>:
68dc0745 362
109f0441
S
363 $/ = '';
364 $header = <MSG>;
365 $header =~ s/\n\s+/ /g; # merge continuation lines
366 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
68dc0745 367
368That solution doesn't do well if, for example, you're trying to
369maintain all the Received lines. A more complete approach is to use
589a5df2 370the C<Mail::Header> module from CPAN (part of the C<MailTools> package).
68dc0745 371
372=head2 How do I decode a CGI form?
373
7678cced
RGS
374(contributed by brian d foy)
375
589a5df2 376Use the C<CGI.pm> module that comes with Perl. It's quick,
7678cced
RGS
377it's easy, and it actually does quite a bit of work to
378ensure things happen correctly. It handles GET, POST, and
379HEAD requests, multipart forms, multivalued fields, query
380string and message body combinations, and many other things
381you probably don't want to think about.
382
589a5df2 383It doesn't get much easier: the C<CGI.pm> module automatically
7678cced
RGS
384parses the input and makes each value available through the
385C<param()> function.
386
387 use CGI qw(:standard);
6670e5e7 388
9e72e4c6 389 my $total = param( 'price' ) + param( 'shipping' );
6670e5e7 390
9e72e4c6 391 my @items = param( 'item' ); # multiple values, same field name
6670e5e7 392
589a5df2 393If you want an object-oriented approach, C<CGI.pm> can do that too.
7678cced
RGS
394
395 use CGI;
6670e5e7 396
7678cced 397 my $cgi = CGI->new();
6670e5e7 398
9e72e4c6 399 my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );
6670e5e7 400
9e72e4c6 401 my @items = $cgi->param( 'item' );
7678cced 402
589a5df2 403You might also try C<CGI::Minimal> which is a lightweight version
7678cced
RGS
404of the same thing. Other CGI::* modules on CPAN might work better
405for you, too.
406
407Many people try to write their own decoder (or copy one from
408another program) and then run into one of the many "gotchas"
3bc3c5be 409of the task. It's much easier and less hassle to use C<CGI.pm>.
68dc0745 410
5a964f20 411=head2 How do I check a valid mail address?
68dc0745 412
322be77c 413(partly contributed by Aaron Sherman)
68dc0745 414
322be77c 415This isn't as simple a question as it sounds. There are two parts:
c8db1d39 416
322be77c 417a) How do I verify that an email address is correctly formatted?
c8db1d39 418
322be77c 419b) How do I verify that an email address targets a valid recipient?
c8db1d39 420
322be77c
RGS
421Without sending mail to the address and seeing whether there's a human
422on the other end to answer you, you cannot fully answer part I<b>, but
423either the C<Email::Valid> or the C<RFC::RFC822::Address> module will do
424both part I<a> and part I<b> as far as you can in real-time.
425
426If you want to just check part I<a> to see that the address is valid
427according to the mail header standard with a simple regular expression,
428you can have problems, because there are deliverable addresses that
429aren't RFC-2822 (the latest mail header standard) compliant, and
430addresses that aren't deliverable which, are compliant. However, the
431following will match valid RFC-2822 addresses that do not have comments,
432folding whitespace, or any other obsolete or non-essential elements.
433This I<just> matches the address itself:
434
109f0441
S
435 my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+};
436 my $dot_atom = qr{$atom(?:\.$atom)*};
437 my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"};
438 my $local = qr{(?:$dot_atom|$quoted)};
439 my $quotedpair = qr{\\[\x00-\x09\x0B-\x0c\x0e-\x7e]};
440 my $domain_lit = qr{\[(?:$quotedpair|[\x21-\x5a\x5e-\x7e])*\]};
441 my $domain = qr{(?:$dot_atom|$domain_lit)};
442 my $addr_spec = qr{$local\@$domain};
322be77c
RGS
443
444Just match an address against C</^${addr_spec}$/> to see if it follows
445the RFC2822 specification. However, because it is impossible to be
446sure that such a correctly formed address is actually the correct way
447to reach a particular person or even has a mailbox associated with it,
448you must be very careful about how you use this.
c8db1d39 449
322be77c
RGS
450Our best advice for verifying a person's mail address is to have them
451enter their address twice, just as you normally do to change a
452password. This usually weeds out typos. If both versions match, send
453mail to that address with a personal message. If you get the message
454back and they've followed your directions, you can be reasonably
455assured that it's real.
68dc0745 456
c8db1d39
TC
457A related strategy that's less open to forgery is to give them a PIN
458(personal ID number). Record the address and PIN (best that it be a
322be77c 459random one) for later processing. In the mail you send, ask them to
c8db1d39 460include the PIN in their reply. But if it bounces, or the message is
b432a672 461included via a "vacation" script, it'll be there anyway. So it's
c8db1d39
TC
462best to ask them to mail back a slight alteration of the PIN, such as
463with the characters reversed, one added or subtracted to each digit, etc.
46fc3d4c 464
68dc0745 465=head2 How do I decode a MIME/BASE64 string?
466
589a5df2 467The C<MIME-Base64> package (available from CPAN) handles this as well as
6a0af2f1 468the MIME/QP encoding. Decoding BASE64 becomes as simple as:
68dc0745 469
109f0441
S
470 use MIME::Base64;
471 $decoded = decode_base64($encoded);
68dc0745 472
3bc3c5be 473The C<MIME-Tools> package (available from CPAN) supports extraction with
6a0af2f1
GA
474decoding of BASE64 encoded attachments and content directly from email
475messages.
476
477If the string to decode is short (less than 84 bytes long)
589a5df2 478a more direct approach is to use the C<unpack()> function's "u"
68dc0745 479format after minor transliterations:
480
109f0441
S
481 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
482 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
483 $len = pack("c", 32 + 0.75*length); # compute length byte
484 print unpack("u", $len . $_); # uudecode and print
68dc0745 485
5a964f20 486=head2 How do I return the user's mail address?
68dc0745 487
589a5df2 488On systems that support getpwuid, the C<< $< >> variable, and the
489C<Sys::Hostname> module (which is part of the standard perl distribution),
68dc0745 490you can probably try using something like this:
491
109f0441
S
492 use Sys::Hostname;
493 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
68dc0745 494
5a964f20
TC
495Company policies on mail address can mean that this generates addresses
496that the company's mail system will not accept, so you should ask for
497users' mail addresses when this matters. Furthermore, not all systems
68dc0745 498on which Perl runs are so forthcoming with this information as is Unix.
499
3bc3c5be 500The C<Mail::Util> module from CPAN (part of the C<MailTools> package) provides a
589a5df2 501C<mailaddress()> function that tries to guess the mail address of the user.
68dc0745 502It makes a more intelligent guess than the code above, using information
503given when the module was installed, but it could still be incorrect.
504Again, the best way is often just to ask the user.
505
c8db1d39 506=head2 How do I send mail?
68dc0745 507
c8db1d39
TC
508Use the C<sendmail> program directly:
509
109f0441
S
510 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
511 or die "Can't fork for sendmail: $!\n";
512 print SENDMAIL <<"EOF";
513 From: User Originating Mail <me\@host>
514 To: Final Destination <you\@otherhost>
515 Subject: A relevant subject line
c8db1d39 516
109f0441
S
517 Body of the message goes here after the blank line
518 in as many lines as you like.
519 EOF
520 close(SENDMAIL) or warn "sendmail didn't close nicely";
c8db1d39 521
3bc3c5be 522The B<-oi> option prevents C<sendmail> from interpreting a line consisting
c8db1d39
TC
523of a single dot as "end of message". The B<-t> option says to use the
524headers to decide who to send the message to, and B<-odq> says to put
525the message into the queue. This last option means your message won't
526be immediately delivered, so leave it out if you want immediate
527delivery.
528
3bc3c5be 529Alternate, less convenient approaches include calling C<mail> (sometimes
530called C<mailx>) directly or simply opening up port 25 have having an
d92eb7b0 531intimate conversation between just you and the remote SMTP daemon,
3bc3c5be 532probably C<sendmail>.
d92eb7b0 533
3bc3c5be 534Or you might be able use the CPAN module C<Mail::Mailer>:
c8db1d39 535
109f0441 536 use Mail::Mailer;
c8db1d39 537
109f0441
S
538 $mailer = Mail::Mailer->new();
539 $mailer->open({ From => $from_address,
540 To => $to_address,
541 Subject => $subject,
542 })
543 or die "Can't open: $!\n";
544 print $mailer $body;
545 $mailer->close();
c8db1d39 546
589a5df2 547The C<Mail::Internet> module uses C<Net::SMTP> which is less Unix-centric than
548C<Mail::Mailer>, but less reliable. Avoid raw SMTP commands. There
3bc3c5be 549are many reasons to use a mail transport agent like C<sendmail>. These
8305e449 550include queuing, MX records, and security.
c8db1d39 551
575cc754
JH
552=head2 How do I use MIME to make an attachment to a mail message?
553
589a5df2 554This answer is extracted directly from the C<MIME::Lite> documentation.
575cc754
JH
555Create a multipart message (i.e., one with attachments).
556
109f0441 557 use MIME::Lite;
575cc754 558
109f0441
S
559 ### Create a new multipart message:
560 $msg = MIME::Lite->new(
561 From =>'me@myhost.com',
562 To =>'you@yourhost.com',
563 Cc =>'some@other.com, some@more.com',
564 Subject =>'A message with 2 parts...',
565 Type =>'multipart/mixed'
566 );
575cc754 567
109f0441
S
568 ### Add parts (each "attach" has same arguments as "new"):
569 $msg->attach(Type =>'TEXT',
570 Data =>"Here's the GIF file you wanted"
571 );
572 $msg->attach(Type =>'image/gif',
573 Path =>'aaa000123.gif',
574 Filename =>'logo.gif'
575 );
575cc754 576
109f0441 577 $text = $msg->as_string;
575cc754 578
589a5df2 579C<MIME::Lite> also includes a method for sending these things.
575cc754 580
109f0441 581 $msg->send;
575cc754 582
197aec24 583This defaults to using L<sendmail> but can be customized to use
575cc754
JH
584SMTP via L<Net::SMTP>.
585
c8db1d39
TC
586=head2 How do I read mail?
587
589a5df2 588While you could use the C<Mail::Folder> module from CPAN (part of the
589C<MailFolder> package) or the C<Mail::Internet> module from CPAN (part
590of the C<MailTools> package), often a module is overkill. Here's a
d92eb7b0
GS
591mail sorter.
592
109f0441
S
593 #!/usr/bin/perl
594
595 my(@msgs, @sub);
596 my $msgno = -1;
597 $/ = ''; # paragraph reads
598 while (<>) {
599 if (/^From /m) {
600 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
601 $sub[++$msgno] = lc($1) || '';
602 }
603 $msgs[$msgno] .= $_;
604 }
605 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
606 print $msgs[$i];
607 }
c8db1d39 608
d92eb7b0 609Or more succinctly,
c8db1d39 610
109f0441
S
611 #!/usr/bin/perl -n00
612 # bysub2 - awkish sort-by-subject
613 BEGIN { $msgno = -1 }
614 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
615 $msg[$msgno] .= $_;
616 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
c8db1d39 617
a05e4845
RGS
618=head2 How do I find out my hostname, domainname, or IP address?
619X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa,
620gethostbyname, Socket, Net::Domain, Sys::Hostname>
68dc0745 621
a05e4845 622(contributed by brian d foy)
68dc0745 623
589a5df2 624The C<Net::Domain> module, which is part of the standard distribution starting
a05e4845
RGS
625in perl5.7.3, can get you the fully qualified domain name (FQDN), the host
626name, or the domain name.
68dc0745 627
a05e4845 628 use Net::Domain qw(hostname hostfqdn hostdomain);
58103a2e 629
a05e4845
RGS
630 my $host = hostfqdn();
631
632The C<Sys::Hostname> module, included in the standard distribution since
633perl5.6, can also get the hostname.
68dc0745 634
a05e4845 635 use Sys::Hostname;
58103a2e 636
a05e4845 637 $host = hostname();
68dc0745 638
a05e4845
RGS
639To get the IP address, you can use the C<gethostbyname> built-in function
640to turn the name into a number. To turn that number into the dotted octet
641form (a.b.c.d) that most people expect, use the C<inet_ntoa> function
3bc3c5be 642from the C<Socket> module, which also comes with perl.
a05e4845 643
109f0441 644 use Socket;
58103a2e 645
109f0441
S
646 my $address = inet_ntoa(
647 scalar gethostbyname( $host || 'localhost' )
648 );
68dc0745 649
650=head2 How do I fetch a news article or the active newsgroups?
651
589a5df2 652Use the C<Net::NNTP> or C<News::NNTPClient> modules, both available from CPAN.
a6dd486b 653This can make tasks like fetching the newsgroup list as simple as
68dc0745 654
109f0441
S
655 perl -MNews::NNTPClient
656 -e 'print News::NNTPClient->new->list("newsgroups")'
68dc0745 657
658=head2 How do I fetch/put an FTP file?
659
f61c8e37 660(contributed by brian d foy)
661
c69ca1d4 662The C<LWP> family of modules (available on CPAN as the libwww-perl distribution)
f61c8e37 663can work with FTP just like it can with many other protocols. C<LWP::Simple>
664makes it quite easy to fetch a file:
665
666 use LWP::Simple;
84adb724 667
f61c8e37 668 my $data = get( 'ftp://some.ftp.site/some/file.txt' );
84adb724 669
670If you want more direct or low-level control of the FTP process, you can use
f61c8e37 671the C<Net::FTP> module (in the Standard Library since Perl 5.8). It's
672documentation has examples showing you just how to do that.
68dc0745 673
674=head2 How can I do RPC in Perl?
675
f61c8e37 676(contributed by brian d foy)
b68463f7
RGS
677
678Use one of the RPC modules you can find on CPAN (
679http://search.cpan.org/search?query=RPC&mode=all ).
68dc0745 680
681=head1 AUTHOR AND COPYRIGHT
682
8d2e243f 683Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
7678cced 684other authors as noted. All rights reserved.
5a964f20 685
5a7beb56
JH
686This documentation is free; you can redistribute it and/or modify it
687under the same terms as Perl itself.
5a964f20
TC
688
689Irrespective of its distribution, all code examples in this file
690are hereby placed into the public domain. You are permitted and
691encouraged to use this code in your own programs for fun
692or for profit as you see fit. A simple comment in the code giving
693credit would be courteous but is not required.