Question:
How can I send an email in java?
a-nerd
2010-09-25 18:11:27 UTC
Looking at the java EE documentation, I can see there is something to do with mail there. But exactly what commands would I use? Would it require a password? And, perhaps most important, can I send it with my yahoo mail account?
Three answers:
Mohamed Mansour
2010-09-25 19:06:15 UTC
Hi,



Sending an email in Java is relatively made simple with the JavaMail API:

http://www.oracle.com/technetwork/java/index-jsp-139225.html



You can set your Yahoo's SMTP settings:

server: smtp.mail.yahoo.com use ssl

login/password: your email address without the “@yahoo.com”



You can find many examples when you download the zip from JavaMail:

http://www.oracle.com/technetwork/java/downloads-137827.html



As a start, you can use this example (untested);

http://gist.github.com/597504

=================

// Email message

String toAddress = "someone@example.com";

String fromAddress = "hello@mohamedmansour.com";

String subject = "Hello Yahoo!"

String message = "From Java!";



// Auth.

String host = "smtp.mail.yahoo.com";

String port = "465";

String username = "foo";

String password = "bar";



// Configure your JavaMail.

Properties props = new Properties();

props.setProperty( "mail.transport.protocol", "smtps");

props.setProperty( "mail.smtps.auth", "true");

props.setProperty( "mail.host", host);

props.setProperty( "mail.port", port);

props.setProperty( "mail.user", username);

props.setProperty( "mail.password", password);



// Start an email session.

Session session = Session.getDefaultInstance(props, null);

Transport transport = session.getTransport("smtp");

MimeMessage mimeMessage = new MimeMessage(session);

Multipart multiPart = new MimeMultipart();



mimeMessage.setSubject( subject);

mimeMessage.addRecipient( RecipientType.TO, new InternetAddress(toAddress));

MimeBodyPart textBodyPart = new MimeBodyPart();

textBodyPart.setContent( message, "text/plain");

multiPart.addBodyPart( textBodyPart);

mimeMessage.setContent( multiPart);

mimeMessage.setFrom( new InternetAddress(fromAddress));



// Send email.

transport.connect();

transport.sendMessage( mimeMessage, mimeMessage.getAllRecipients() );

transport.close();

=================



Hope that helped!
ferer
2016-10-15 10:05:06 UTC
Java Code To Send Email
WilliamG
2010-09-25 18:13:10 UTC
It should be the same there as it is where you live.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...