我複製了「quickstart:發送Gmail」中的代碼並修改了一些內容給我的應用程序。該代碼似乎工作正常,但發件人的名稱沒有得到設置,無論我如何嘗試它。在使用Gmail發送電子郵件時使用Java設置發件人姓名
這裏是我的完整代碼:
import java.util.Arrays;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
public class Test{
\t private static final String SCOPE = "https://www.googleapis.com/auth/gmail.modify";
\t private static final String APP_NAME = "XYZ";
\t // Path to the client_secret.json file deloper Console
\t private static final String CLIENT_SECRET_PATH = "src/testapp/auth_client.json";
\t private static GoogleClientSecrets clientSecrets;
\t private static GoogleAuthorizationCodeFlow flow;
\t private static HttpTransport httpTransport;
\t private static JsonFactory jsonFactory;
\t private static Gmail service;
\t public static String getRequestUrl() throws FileNotFoundException, IOException{
\t \t httpTransport = new NetHttpTransport();
\t \t jsonFactory = new JacksonFactory();
\t \t
\t \t clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(
\t \t \t \t CLIENT_SECRET_PATH));
\t \t
\t \t // Allow user to authorize via url.
\t \t flow = new GoogleAuthorizationCodeFlow.Builder(
\t \t \t \t httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
\t \t .setAccessType("online").setApprovalPrompt("auto").build();
\t \t
\t \t String url = flow.newAuthorizationUrl()
\t \t \t \t .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
\t \t
\t \t return url;
\t }
\t
\t public static void sendMail(String to, String sub, String body) throws IOException, MessagingException {
\t \t Message message = createMessageWithEmail(createEmail(to, "me", sub, body));
\t message = service.users().messages().send("me", message).execute();
\t
\t System.out.println("Message id: " + message.getId());
\t System.out.println(message.toPrettyString());
\t }
\t static void emailCredentialSetup(String code) throws IOException {
\t \t // Generate Credential using retrieved code.
\t \t GoogleTokenResponse response = flow.newTokenRequest(code)
\t \t \t \t .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
\t \t \t \t .execute();
\t \t GoogleCredential credential = new GoogleCredential()
\t \t \t \t .setFromTokenResponse(response);
\t \t // Create a new authorized Gmail API client
\t \t service = new Gmail.Builder(httpTransport, jsonFactory,
\t \t \t \t credential).setApplicationName(APP_NAME).build();
\t }
\t
\t /**
\t * Create a MimeMessage using the parameters provided.
\t *
\t * @param to Email address of the receiver.
\t * @param from Email address of the sender, the mailbox account.
\t * @param subject Subject of the email.
\t * @param bodyText Body text of the email.
\t * @return MimeMessage to be used to send email.
\t * @throws MessagingException
\t * @throws UnsupportedEncodingException
\t */
\t private static MimeMessage createEmail(String to, String from, String subject,
\t String bodyText) throws MessagingException, UnsupportedEncodingException {
\t Properties props = new Properties();
\t Session session = Session.getDefaultInstance(props, null);
\t MimeMessage email = new MimeMessage(session);
\t email.setFrom(new InternetAddress(from, "SPecial message"));
\t email.addRecipient(javax.mail.Message.RecipientType.TO,
\t new InternetAddress(to));
\t email.setSubject(subject);
\t email.setText(bodyText);
\t return email;
\t }
\t
\t /**
\t * Create a Message from an email
\t *
\t * @param email Email to be set to raw of message
\t * @return Message containing base64 encoded email.
\t * @throws IOException
\t * @throws MessagingException
\t */
\t private static Message createMessageWithEmail(MimeMessage email)
\t throws MessagingException, IOException {
\t ByteArrayOutputStream baos = new ByteArrayOutputStream();
\t email.writeTo(baos);
\t String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
\t Message message = new Message();
\t message.setRaw(encodedEmail);
\t return message;
\t }
\t
\t public static void main(String[] args) throws FileNotFoundException, IOException, MessagingException {
\t \t System.out.println(getRequestUrl());
\t \t BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
\t \t emailCredentialSetup(br.readLine());
\t \t
\t \t sendMail("[email protected]", "TEST1", "Hello");
\t }
}
有人可以幫我在發件人名稱設置爲自定義字符串?我嘗試了一些谷歌搜索後設置名稱爲「SPecial消息」,但它不起作用。
謝謝你的回答@Eric DeFriez。我現在想用授權的用戶名替換「我」。因爲,我沒有直接從用戶那裏得到它,你如何建議我取回它? – 2015-03-06 10:54:50
爲什麼不完全避免From頭?如果未提供,則Gmail API將爲用戶設置默認的一個,這可能是您想要的。 – 2015-03-06 17:06:32
對於要求@Eric DeFriez的要求是正確的,但完全刪除From標題不會讓默認標題顯示出來。我評論過「email.setFrom(新的InternetAddress(來自」,「特權消息」));「在上面的代碼行和默認名稱正在顯示。 – 2015-03-08 13:22:14