Get it on Google Play

Enviar mail en PHP i Java

23-08-2006
 

Un tros de codi molt necessari en qualsevol aplicació Web actual:

En PHP:


function sendMail($to,$subject,$message) {
  ini_set("SMTP","elMeuSmtp.com");

  // Envio missatge ***
  $cabeceras = "From: ".getenv("HTTP_HOST")."\\r\\nContent-type: text/html; charset=iso-8859-1\\r\\n";
  mail($to, $subject, $message, $cabeceras );
  }

En Java:


import java.util.Properties;
import java.util.StringTokenizer;
import java.security.Security;
import javax.mail.*;
import javax.mail.internet.*;

public boolean send(String to, String tema, String contingut) {
  try {
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", smtpHost);
    properties.put("mail.smtp.port", smtpPort);
    properties.put("mail.smtp.auth", "true");
    if (smtpSSL) properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

javax.mail.Authenticator authenticator = new javax.mail.Authenticator() {
public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUser, smtpPass); }
};

    Session session = Session.getDefaultInstance(properties, authenticator);

    MimeMessage mimemessage = new MimeMessage(session);
    mimemessage.setFrom(new InternetAddress(from));
    
    for(StringTokenizer stringtokenizer = new StringTokenizer(to, ";");
    stringtokenizer.hasMoreTokens();
    mimemessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(stringtokenizer.nextToken())));
    
    mimemessage.setSubject(tema);
    MimeBodyPart mimebodypart = new MimeBodyPart();
    mimebodypart.setContent(contingut, "text/html");
    MimeMultipart mimemultipart = new MimeMultipart();
    
    mimemultipart.addBodyPart(mimebodypart);
    mimemessage.setContent(mimemultipart);
    
    Transport.send(mimemessage);
  } catch(Exception exception) {
    exception.printStackTrace();
    return false;
    }

  return true;
  }

Leave a Reply

© Albert Coronado Calzada