Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javamail API - How do you change setFrom to whatever you want?

How do I change the setFrom() method to whatever I want? I can send e-mails through my gmail accoutn and change the setFrom text, but it shows my username for the email. I have tried using my yahoo account as well and I get an authentication error.

I want to change the from address. The code is as follows:

import java.util.Properties;

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.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties 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 = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            }
        );

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
like image 945
shaunw Avatar asked Dec 01 '12 00:12

shaunw


1 Answers

Faced Same problem while using "smtp.gmail.com". Use Mandrill,it will work. Once you setup a Mandrill account,use "smtp.mandrillapp.com" on port 587. For Authentication,set username=your mandrill username and password=API key generated in your account.

like image 102
Rishi Ghosh Avatar answered Nov 15 '22 07:11

Rishi Ghosh