Imagen:
Código:
package elrinconprograues.mail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * * @author Alex Callejas */ public class SendMail { public static final String Username = "example@gmail.com"; public static final String PassWord = "password"; static Session session; static Properties props; public SendMail() { } public Session sessionMail() { props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Username, PassWord); } }); return session; } public void send(String to,String msg){ try { Message message = new MimeMessage(sessionMail()); message.setFrom(new InternetAddress(Username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("Subject"); message.setText(msg); Transport.send(message); } catch (MessagingException e) { System.out.println(e.getMessage()); } } public void send(String to,String msg,String srcAttached){ try { sessionMail(); BodyPart attached = new MimeBodyPart(); BodyPart texto = new MimeBodyPart(); texto.setText(msg); MimeMultipart multiParte = new MimeMultipart(); attached.setDataHandler( new DataHandler(new FileDataSource(srcAttached))); attached.setFileName("File Name"); multiParte.addBodyPart(texto); multiParte.addBodyPart(attached); Message message = new MimeMessage(sessionMail()); message.setFrom(new InternetAddress(Username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("Subject"); message.setContent(multiParte); message.setText(msg); message.setContent(multiParte); Transport.send(message); } catch (MessagingException ex) { System.out.println(ex.getMessage()); } } public static void main(String[] args) { SendMail sendMail=new SendMail(); sendMail.send("example@mail.com", "Esta es una prueba de envio de correos con java"); } }Descarga: Mega
No hay comentarios :
Publicar un comentario